Iulian Rosca
Iulian Rosca

Reputation: 1015

Send JSON object with POST

I want to send a JSON object with POST

var user = {
    "first_name": first_name.value,
    "last_name": last_name.value,
    "age": age.value,
    "email": email.value
};   

This is how I send the object :

var request;
var url = 'ajax_serverside_JSON.php';
var destination;

function ajax_call(src, jsonObj, dst, method) {

    this.src = src;
    destination = dst;
    this.objJSON = jsonObj;
    this.request = getXMLHttpRequest();
    this.request.onreadystatechange = getResponse;
    if (method == 'POST') {
        sendPostRequest(objJSON);
    }
    return;
}

function sendPostRequest(objJSON) {
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.send(JSON.stringify(objJSON));
    return;
}

function getXMLHttpRequest() {
    try {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera,Safari
            request = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    } catch (e) {
        alert('The browser doesn\'t support AJAX: ' + e);
        request = false;
    }
    return request;
}

function getResponse() {
    if (request.readyState == 4 && request.status == 200) {
        document.getElementById(destination).innerHTML += request.response;
    }
}

Question: how do I read the object in the server side php ? What is the key o the sent json ?

echo var_dump ( $_POST ); shows

  array (size=0)
  empty

What is the problem?

AFTER EDIT

I changed my code to :

this.objJSON = jsonObj;

and

request.send("user=" + JSON.stringify(this.objJSON));

I try reading the JSON obj :

<?php
if (isset ( $_POST ['user'] )) {
    $obj = json_decode ( $_POST ['user'] );
    echo "isset";
} else {
    echo "is not set ";
    echo var_dump ( $_POST );
}
?>

...and still the same thing :

is not set

array (size=0)
  empty

Upvotes: 3

Views: 40923

Answers (6)

Tom Rutchik
Tom Rutchik

Reputation: 1692

I'll try to bring some clarity to the original question and perhaps clear up some potential confusion. Rosca's question or confusion is that $_POST doesn't work in PHP when Posting a JSON object. The reason is that the original request, although being done as a post is not being sent as a standard "forms" post request. In a standard forms post, the request Content-Type should be "application/x-www-form-urlencoded" and not "application/json". In addition, the body of the post request should be a url-encoded query string and not a JSON encoded string. They are formatted differently. A query string might look like id=134626&type=car, where as a JSON encoded string would look like ["id"="134526","type":"car"]. Because the way the original request was sent, it's sending JSON object data and not URL encoded forms data. So, PHP returns an error when you do something like $_POST["id"], because no forms data was sent. The suggestions that others have offered is having PHP read the request body and process it as a JSON object. If you're sending the post request as a JSON object and processing it on the server side as a JSON object, that works perfectly fine!

The other thing you could do is to send the data as url encoded forms data content (application/x-www-form-urlencoded), add the data as a valid query string, and process it on the server side as a standard forms post request. If you do it that way, then yes, you can use $_POST["id"] in PHP to get the value of the "id" parameter. Here's some javascript code that converts a JSON object to a query string:

function obj2qs(param
 var queryString = "";
 var sep = "";
 $.each(Object(params), function(key, value) {
    var input = document.createElement('input');
    queryString += sep + encodeURIComponent(key) + "=" + encodeURIComponent(value);
    sep = "&";
 });
 return queryString;
}

In the above, "params" is the json object that you want converted into a queryString.

Here's how to make those changes in Rosca's coding so that it is sent like a standard forms post:

function sendPostRequest(objJSON) {
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.send(obj2qs(objJSON));
}

The advantage of sending the request as a standard forms request is that you can easily create a simple html page for testing the page that performs the post operation.

Upvotes: 0

Musa
Musa

Reputation: 97672

For your original Ajax request, you'll have to read the request body from php://input and decode then it.

<?php
$post = json_decode(file_get_contents('php://input'));
if (isset ( $post ['user'] )) {
    echo "isset";
} else {
    echo "is not set ";
    echo var_dump ( $post );
}

Upvotes: 2

phpCore
phpCore

Reputation: 159

<script>
var user = {
                "first_name" : first_name.value,
                "last_name" : last_name.value,
                "age" : age.value,
                "email" : email.value
            };

$.customPOST = function(data,callback){
  $.post('your_php_script.php',data,callback,'json');
}

$(document).ready(function() {
    //suppose you have a button "myButton" to submit your data
    $("#myButton").click(function(){
        $.customPOST(user,function(response){
         //on the server side you will have :
         //$_POST['first_name'], $_POST['last_name'], .....
         //server will return an OBJECT called "response"
         //in "index.php" you will need to use json_encode();
         //in order to return a response to the client
         //json_encode(); must have an array as argument
         //the array must be in the form : 'key' => 'value'
        });
        return false;
    });
</script>

Upvotes: 1

Barmar
Barmar

Reputation: 780974

I'm not sure that PHP can automatically parse JSON into $_POST variables. You should put the JSON into the value of a normal POST variable:

request.send('data=' + encodeURIComponent(JSON.stringify(objJSON));

and use the default Content-Type. Then in PHP you can do:

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

You also need to fix a Javascript variable, as explained in Niels Keurentjes's answer.

Upvotes: 3

Vivek
Vivek

Reputation: 4886

Try :

request.send("obj="+JSON.stringify(objJSON));

its a key value pair, I guess you are missing key.

Upvotes: 2

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

Breaking your function down to its core 3 lines:

function ajax_call(src, jsonObj, dst, method) {

jsonOBJ is set in local scope as a variable.

this.objJSON = jsonObj;

jsonOBJ is copied to this.objJSON.

sendPostRequest(objJSON);

There is still no local variable objJSON since Javascript does not automatically consider this part of the local scope, hence null is sent, hence the empty $_POST.

Send jsonOBJ or this.objJSON instead and it'll work fine.

Upvotes: 2

Related Questions