bsand
bsand

Reputation: 135

Getting data from Ajax POST request in PHP?

I'm trying to send a POST request with Ajax, but I'm having trouble getting the values sent in PHP. Here's my JavaScript code:

$.ajax({
    url: "updatedata.php",
    type: 'post',
    data: JSON.stringify(jsonData),
    contentType: 'application/json',
    dataType: 'json',
    success: function(data, status, xhr)
    {
       //...
    }
});

And I want to access the data with PHP. Something like this?

$data = $_POST['data'];

My data:

{"UID":"00a3b1b0-03b4-11e1-be50-0800200c9a66","Firstname":"Bastian","Lastname":"Sander","UserPenaltys":{"Penalty1":"110","Penalty10":"200","Penalty11":"210","Penalty12":"220","Penalty13":"230","Penalty14":"240","Penalty15":"250","Penalty16":"260","Penalty2":"120","Penalty3":"130","Penalty4":"140","Penalty5":"150","Penalty6":"160","Penalty7":"170","Penalty8":"180","Penalty9":"190"},"PenaltyCounter":16}

I tried this:

$.post("updatedata.php", JSON.stringify(UserData), function (data) {
}, "json");

But $_POST['Firstname'] is empty...

Upvotes: 3

Views: 34717

Answers (3)

MaxXx1313
MaxXx1313

Reputation: 620

$data = $_POST['data']; - that's wrong.

$_POST['UID'], $_POST['Firstname'], $_POST['Lastname'] etc. only be avalable

It can be you even hadn't make some operation like that: JSON.stringify(jsonData); May be will work something like this: $.ajax({..., data: jsonData, ...});

You should try to start some traffic analyzer, for example press F12 in google chrome (tab Network), or select opera dragonfly in opera, or another trafic analyzer and resolve some question: 1. is request send to right script and response not an 404 error 2. is received data has right format? (in google chrome on Network tab, click on request for more info)

i think problem will be resolved by this two steps =)

Upvotes: 2

WWW
WWW

Reputation: 9860

Why not use $.post()? The format is:

$.post(<URI string>, <postdata object>, <handler>, <datatype>);

And then treat the data like any other form post to PHP (i.e. use the $_POST variable).

Upvotes: 3

Naftali
Naftali

Reputation: 146300

Number one: you do not need to use JSON.stringify

Number two: Access them like so:

$uid = $_POST['UID']; //...etc

Upvotes: 2

Related Questions