1

I am getting a string from file_get_contents('php://input'). I tried json_decode(), but the string is not a json. Here is the ajax request and the php code. How can I get the json sent from the ajax request and turn it into a php array?

$data = file_get_contents('php://input');
var_dump($data);
echo $data;

Output:

string(7) "id=myId"
"id=myId"

Ajax(Includes Jquery):

$.ajax({
    "url": "myFile.php",
    "type": "POST",
    "contentType": "Json",
    "data": {"id": "myId"},
}).done(function(data, status) {
    if (status == "success") {
        console.log(data);
    }
}).fail(function(data, status, error) {
    throw new Error(error);
    console.log(data);
    console.log(status);
});

Edit: json_encode() is returning null, so I cannot use the answer from this question: PHP: file_get_contents('php://input') returning string for JSON message

3
  • Possible duplicate of PHP: file_get_contents('php://input') returning string for JSON message Commented May 31, 2017 at 18:10
  • 2
    It's form-encoded. You could decode it yourself, or just access it via $_POST['id'] where PHP has already decoded it. Commented May 31, 2017 at 18:12
  • $_POST["data"] and $_POST["id"] didn't work for me, so I was forced to use file_get_contents('php://input') which did the job Commented May 31, 2017 at 18:19

1 Answer 1

3

Like Sammitch mentioned in his comment, your current code is sending it with form encoding. For what you want, stringify the data before sending it to the server, so that it gets received as JSON. Modify your call to be like this:

$.ajax({
    "url": "myFile.php",
    "type": "POST",
    "contentType": "application/json",
    "data": JSON.stringify({"id": "myId"}),
})

This should result in the input being a json encoded object.

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

1 Comment

Looks like my problem was on the client side, not server side. Now after doing this, json_encode() is working!

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.