dsdtszi0520538
2016-05-07 19:57
浏览 47

我无法通过AJAX将会话存储数据发送到服务器

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyongkui6329 2016-05-07 20:19
    已采纳

    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)";
    
    点赞 打赏 评论

相关推荐 更多相似问题