Cannot retrieve data sent via js Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Cannot retrieve data sent via js without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I use the following to send the data:

$(".save_post").on("click", function() {
  var saveId = $(".my_post_id").attr("data-id");
  console.log(saveId);
  $.ajax({
    url: "save.php",
    data :saveId, 
    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 value when I do console.log(saveId); is 248

And when I click the button to send the data, its text says: Data has been saved.

But when I open save.php i get an empty page.

PHP code:

<?php
    $post_data = $_POST['data'];
    echo $post_data;
?>

All I am trying to do is to save a javascript variable in order to be able to retrieve it later on.

Answer

You forgot to send a key with the value:

data: { data: saveId }

You should also use the data() method to get data-* attributes, not attr(). Here’s a full example:

$(".save_post").on("click", function() {
  $.ajax({
    url: "save.php",
    data: { data: $(".my_post_id").data("id") }, 
    type: 'POST',
    success: function(response) {
      console.log(response);
      $(".save_post").text("Data has been saved.");
    },
    error: function(x, s, e) {
      $(".save_post").text("Failed to save data !");
    }
  });
});

Note that this is assuming you have only a single .my_post_id element. If you have multiple then data-id will only be read from the first one found in the DOM.

Also, there’s no such thing as a ‘JSON object’. The argument provided to the success handler is an object (or array) which has been deserialised from the JSON formatted string in the response.

Similarly, the error handler doesn’t accept an argument which contains JSON, so that signature is incorrect. I’d suggest checking the jQuery $.ajax() documentation if you are unsure on what arguments are available to which jQuery AJAX handlers.

We are here to answer your question about Cannot retrieve data sent via js - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji