将数据从js保存到php失败

将数据从js保存到php失败

问题描述:

I run the following js:

$(".save_post").on("click", function() {
  var saveId = $(".my_post_id").attr("data-id");
  console.log(saveId);
  $.ajax({
    url: "save.php",
    data: saveId,
    dataType: 'json',
    type: 'POST',
    success: function(json_object) {
      console.log(json_object);
      $(".save_post").text("Data has been saved.");
    },
    error: function(json_object) {
      console.log(json_object);
      $(".save_post").text("Failed to save data !");
    }
  });
});

console.log(saveId); gives 248 which is what I would like to save.

PHP page

$post_data = $_POST['data'];
if (!empty($post_data)) {
    $file = fopen('data_save.json', 'w+');
    fwrite($file, json_encode($post_data));
    fclose($file);
    echo json_encode('success');
}
var_dump($post_data);

I get if I go to save.php i get the following and the button text after I click says Failed to save data !

Null

我运行以下js: p>

  $(“。  save_post“)。on(”click“,function(){
 var saveId = $(”。my_post_id“)。attr(”data-id“); 
 console.log(saveId); 
 $ .ajax  ({
 url:“save.php”,
 data:saveId,
 dataType:'json',
 type:'POST',
 success:function(json_object){
 console.log(json_object)  ); 
 $(“。save_post”)。text(“数据已保存。”); 
},
错误:function(json_object){
 console.log(json_object); 
 $(“  .save_post“)。text(”无法保存数据!“); 
} 
}); 
}); 
  code>  pre> 
 
 

console .log(saveId); code>给出 248 code>这就是我要保存的内容。 p>

PHP页面 p> $ post_data = $ _POST ['data']; if(!empty($ post_data)){ $ file = fopen('data_save.json','w +'); fwrite($ file,json_encode($ post_data)); fclose($ file); echo json_encode('success'); } var_dump($ post_data); code> pre> \ 如果我去save.php我就知道了 点击后显示无法保存数据! strong> p> Null code> pre> DIV>

Made it work by removing dataType: 'json',

Try this

$(".save_post").on("click", function() {
    var saveId = $(".my_post_id").attr("data-id");
    console.log(saveId);
    $.ajax({
      url: "save.php",
      data: {saveId:saveId},
      dataType: 'json',
      type: 'POST',
      success: function(json_object) {
        console.log(json_object);
        $(".save_post").text("Data has been saved.");
      },
      error: function(json_object) {
        console.log(json_object);
        $(".save_post").text("Failed to save data !");
      }
    });
});

Data should be passed in ajax like {data:data}