5

Im submitting Data to a php file via AJAX using POST. It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.

In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.

I've tried the following:

this.getAbsence = function()
{
    alert(JSON.stringify(this));
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajax/selectSingle.php?m=getAbsence",
        data: JSON.stringify(this),
        success : function(data){
            alert(data);
        }
    });
}

PHP:

echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));

And:

this.getAbsence = function()
{
    alert(JSON.stringify(this));
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajax/selectSingle.php?m=getAbsence",
        data: {'Absence' : JSON.stringify(this)},
        success : function(data){
            alert(data);
        }
    });
}

PHP:

echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));

The alert was just to check everything is alright...

And yea usual string were echoed correctly :-)

1
  • Im sorry about that, but of course I have to try these answers, and all of them were not right... But yeah I found my answer - but in my opinion I do help if I am commenting why the answer did not help me; if I am not commenting at all the people do not know, if I tried them and if the right answer is already given. Commented Jun 8, 2012 at 12:12

5 Answers 5

23

Where you went wrong in your code in the first code is that you must have used this:

var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']

Quoting from PHP Manual

php://input is a read-only stream that allows you to read raw data from the request body.

Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.

In the second part, you must have used this:

contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),

UPDATE:

When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.

If you must get that using $_POSTyou would make it:

data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},

And then in PHP do:

$json = json_decode($_POST['data']);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, that did it! Tried your answer at last ^^ Though I am a bit confused because I read examples where JSON objects from an ajax call where just echoed from a $_POST... But really thanks :)
Wow, thank you very much with that update it is much more understandable :)
file_get_contents("php://input"); is the one i was looking for. Spent hours before I find this
0

Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.

5 Comments

I don't see how this is relevant at all, as all data is transferred as part of the POST-request and the JSON is formatted by the JSON.stringify-function - single quotes are only used in the object with settings used by the ajax-function.
data: {'Absence' : JSON.stringify(this)} - here, php receives the whole thing, including 'Absence', which should also be in double quotes, otherwise it is not valid.
No, "Absence" is not a property of the given json-object, I am just adressing it with "Absence" to get it via $_POST['Absence'], it ist not a property so it does not have to be in double quotes
As I said - field names should also be in double quotes. See example #3: php.net/manual/en/function.json-decode.php
Yeah, but it is not a fieldname, there will be something submitted like: Absence = aid:1, name:bla... (just pseudo-code) and in fulltext: data: {'Absence':{"aid":1, "name": bla}}; Absence is not part of the object it is the given name
0

To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property. The following should work as you expected:

this.getAbsence = function() {
  var strJSONData = JSON.stringify(this);
  alert(strJSONData);
  jQuery.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: 'ajax/selectSingle.php',
    data: 'm=getAbsence&Absence=' + strJSONData,
    success: function(data) {
      alert(data);
    }
  });
}

4 Comments

strJSONData looks fine, but I am just getting empty strings with "echo $_GET['Absence'];", "echo json_decode($_GET['Absence'])" - also tried with post, but this is a submission as a GET... I thought of doing it via POST or am I misunderstanding something related to the submission of JSON-objects via Ajax? Do they have to be submitted as a GET (url param)?
It should give you empty strings when you access the $_GET variable on a POST request. You could either use the $_POST or the $_REQUEST variable to access the submitted data (etc).
As I told you o tried POST as well, but i tried GET first, because, you are submitting the data like url params, but as I said maybe I am just misunderstanding and the ajay post is kinda a fake "POST" :-)
Ohh I'm sorry, I missed that part of your comment. It's the type that determines how to retrieve the data in your php-script, no matter how the data is formatted – it's just converted to a query-string anyways according to the docs.
0

try this

  var vThis = this;
  this.getAbsence = function()
  {
    alert(JSON.stringify(vThis));
    jQuery.ajax({
       type: "POST",
       contentType: "application/json; charset=utf-8",
       url: "ajax/selectSingle.php?m=getAbsence",
       data: JSON.stringify(vThis),
       success : function(data){
         alert(data);
       } 
     });
   }

EDIT

I think we can also do this!

  var vThis = this;
  this.getAbsence = function()
  {
    alert(JSON.stringify(vThis));
    jQuery.ajax({
       type: "POST",
       dataType: "json",
       url: "ajax/selectSingle.php?m=getAbsence",
       data: vThis,
       success : function(data){
         alert(data);
       } 
     });
   }

and in PHP

print_r($_POST);

5 Comments

The reference this in the function body should be a reference to the object on which the function was called, so that part should work even if it's not exactly pretty or readable code
yes, alert will work, but the this in jQuery.ajax will not be the reference to the object on which the function was called
One good point u have, that this might not be the object anymore, though I do not think so, because I have seen other examples where this was used directly. Your second suggestions leads to an erro in the console: "too much recursion" - Don't know why, my browser even freezes for a moment x) the first one by print_r($_POST) I am only getting "Array()" of course and $_POST['data'] ist empty :-/
are you binding this.getAbsence to the DOM ? If so, then second option will not work.
No, I am not :-/ function Absence(){this.aid;this.eid;...[my method]...} in another js: myAbsence = new Absence(); myAbsence.aid = 1; myAbsence.getAbsence(); - But anyways I found my answer, but maybe it helps u or u have something so say sumething like "OMG, what are u doin?" ^^
0

On PHP side try this:

$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.