0

I have the below code running to send data as a JSON object

var jdata = JSON.stringify(grid.serialize());
$.ajax({
    'type': 'POST',
    'url': 'print.php',
    'data': jdata, //assuming you have the JSON library linked.
    'contentType': "application/json",
    'success': function (data) {
        alert(data);
    },
    'error': function (x, y, z) {
        alert(x.responseText);
        // x.responseText should have what's wrong
    }
});
alert(JSON.stringify(grid.serialize()));

Currenty the alert after the ajax function prints

[{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}]

On the receiving page I am using <?php print_r($_POST) ?> to see what the page is being sent and it keeps outputting

Array
(
)

I must be missing something simple but have been unable to figure out what. Maybe a fresh set of eyes will see a simple mistake I have made.

5
  • Just a quick guess... I think you must write post in lowercase. Otherwise... did you try with $.post? Commented May 18, 2013 at 12:12
  • Are you posting [{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}] as is? Commented May 18, 2013 at 12:13
  • 1
    it doesn't matter if post in uppercase. Commented May 18, 2013 at 12:14
  • Launch Fiddler, fiddler2.com, or a similar tool to examine your form Post. Commented May 18, 2013 at 12:15
  • @Bimal: The problem here has nothing to do with cross-domain issues. Commented May 18, 2013 at 12:30

2 Answers 2

2

I think $_POST is only populated if you send the data encoded as x-www-form-urlencoded. So, just assign the JSON string to a key (jQuery takes care of encoding it properly):

'data': {data: jdata}

and remove the 'contentType': "application/json" part.

Then you get the data in PHP with:

$data = json_decode($_POST['data'], true);

Alternatively, get the raw body of the request in PHP and process it: How to retrieve Request Payload

Sign up to request clarification or add additional context in comments.

2 Comments

I tried this method and it passes the json array but backsashes a of the double quotes
Then you should probably disable magic quotes: stackoverflow.com/questions/6642901/…
0

If you are sending JSON to the server, on the back-end grab your JSON using:

json_decode(file_get_contents('php://input'));

It won't be in the $_POST super global.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.