0

I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:

var noteData =  { 
    nData: {
        "postID": $postID,
        "commentPar": $commentPar,
        "commentValue": $commentValue
    } 
}
var sendData = JSON.stringify(noteData);

$.ajax({
    type: "POST",
    url: templateUrl+"/addnote.php",
    data: sendData,
    dataType : 'json',
    success: function(data) { 
        alert(data);
        console.log(sendData);
    },
    error: function(e) {
        console.log(e.message);
        console.log(noteData);
        console.log(sendData);
        alert("error");
    }
});

Here is how I just test if the data is even being passed to PHP, it always returns back null.

<?php
  $nData = json_decode($_POST['nData']);
  echo json_encode($nData);
?>

What am I doing wrong?

2
  • @Pekka웃 explain that please? Commented Jun 8, 2013 at 13:42
  • I somehow misread that you decode it at first (even though I thought I double-checked), sorry. Disregard. Commented Jun 8, 2013 at 13:52

2 Answers 2

2

You are sending the data as raw JSON to PHP, not as POST parameter.

There are two alternatives. The first one leaves your PHP intact:

var noteData =  { 
    nData: {
        "postID": $postID,
        "commentPar": $commentPar,
        "commentValue": $commentValue
    } 
}
var sendData = JSON.stringify(noteData);

$.ajax({
    type: "POST",
    url: templateUrl+"/addnote.php",
    data: {
        nData: sendData
    },
    dataType : 'json',
    success: function(data) { 
        alert(data);
        console.log(sendData);
    },
    error: function(e) {
        console.log(e.message);
        console.log(noteData);
        console.log(sendData);
        alert("error");
    }
});

The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.

<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);

This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.

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

2 Comments

The second solution worked, the first one still gave me null. I was wondering which one is considered best practice, or more secure?
Security is equivalent on both sides. As for the best practice, I would probably go with the second one if you need to send complex data structures.
0

Tell your post request that you are sending json object contentType: "application/json"

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.