Kshitij Pandey Kshitij Pandey - 7 months ago 74
Javascript Question

I am not able to send session storage data through AJAX to the server

I have stored the ID of the user in session storage. I need to perform an action using the ID so I am passing it to the server using AJAX but the data is not reaching the server.

AJAX:-

$(document).ready(function(){
$('#coupon_code').hide();
$('#coupon_status').hide();
var id = sessionStorage.getItem('user_id');

$('#generate').click(function(){
$.ajax({
type : "POST",
dataType : 'json',
url : 'http://127.0.0.1/ionic/generate.php',
data : id,
beforeSend : function(){
console.log(sessionStorage.getItem('user_id'));
console.log("data sent");
},
success : function(data){
console.log(data);
console.log(data.code);
console.log(data.value);
}
});
});
});


PHP script:-

<?php
require 'db_connect.php';
header('Access-Control-Allow-Origin: *');
$id = $_POST['id'];

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';

for ($i = 0; $i < 5; $i++) {
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
$ins = "INSERT INTO `coupon_code` (id,code,status) VALUES ('$id,'$string',1)";
$res_ins = mysqli_query($con,$ins);

if($res_ins)
{
echo json_encode(array("status" => "done", "code" => $string,"value" => "1"));
//echo $string;
}
else
{
echo "NO";
}
?>


EDIT :-
Firebug result
enter image description here

Answer

You are only sending value in json data - you need to send key-value pair - so through key you will get data at server

This should work for you - also you can debug data in firebug what is going to server or not

You need to replace This line data : id,

with this line data : {'id' : id},

 $(document).ready(function(){
      $('#coupon_code').hide();
      $('#coupon_status').hide();
      var id = sessionStorage.getItem('user_id');

      $('#generate').click(function(){
        $.ajax({
          type : "POST",
          dataType : 'json',
          url : 'http://127.0.0.1/ionic/generate.php',
          data : {'id' : id},
          beforeSend : function(){
            console.log(sessionStorage.getItem('user_id'));
            console.log("data sent");
          },
          success : function(data){
            console.log(data);
            console.log(data.code);
            console.log(data.value);
          }
        });
      });
    });

There is also a bug in insert query -

$ins = "INSERT INTO `coupon_code` (id,code,status) VALUES ('$id,'$string',1)";

(')single quote not closed for '$id

$ins = "INSERT INTO `coupon_code` (id,code,status) VALUES ('$id','$string',1)";