Skip to content Skip to sidebar Skip to footer

Posting JSON String To PHP Page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my prob

Solution 1:

Try:

  $.ajax({
    // ...
    data: { data: JSON.stringify(photo_annotations) },
    // ...
  });

If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.


Solution 2:

Try urldecode or rawurldecode as follows:

<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>

Solution 3:

I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:

var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
    url: 'ajax/save-annotations',
    type: 'POST',
    data: post_data,
    dataType: 'html',
    success: function(data) {
        $('#form_results').html(data);
    }
});

The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!

var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
    type: 'POST',
    dataType: 'html',
    data: data_str,
    url: 'ajax/save-annotations.php',
    success: function(data) {
        $('#form_results').html(data);
    }
});

Solution 4:

in your ajax call try resetting the dataType to json

dataType: "json",

You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.


Post a Comment for "Posting JSON String To PHP Page"