Home » Php » passing JavaScript object to PHP not working

passing JavaScript object to PHP not working

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to send my javascript object to PHP via JSON.stringify()

Javascript:

$('#save').on('click touch', function(){
    obj = {
        "1" : {
            "1" : "hey",
            "2" : "hay"
            },              
        "2" : {
            "1" : "hey",
            "2" : "hay"
            }
    }

    var json = JSON.stringify( obj );
    console.log(json)
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        success: function(data) {
            alert(data);
            $("p").text(data);
        }
    });
});

ajax.php:

<?php 
    $obj = json_decode($json);
    echo $obj;
?> 

But this code returns an error saying that $json is not defined.
I have no idea why this is not working.

How to&Answers:

There are 2 problems.

  1. You are not sending any data with the request
  2. That’s not the way you’ll get the value from a request in PHP

First, add this*:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : { json: json }, // <---------------------
    ...

* this works just because jQuery implementation will automatically convert any non-string data argument into a form-urlencoded query string. See the docs.

Then, in your PHP, you should do:

$jsonStr = $_POST['json'];
$json = json_decode($jsonStr);

Edit:

Another possible way:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : json , // <---------------------
    ...

This way, your data will not be a valid form-urlencoded input, so PHP will not parse it into $_POST, but you still can get the contents of your input doing this:

$jsonStr = file_get_contents("php://input");
$json = json_decode($jsonStr);

Answer:

Well – you never pass your data in the AJAX request!

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: json //<---- RIGHT HERE
    success: function(data) {
        alert(data);
        $("p").text(data);
    }
});

Answer:

You have to send the obj with the ajax request

 $.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : json,
    dataType : 'json' // for json response
    ...

Answer:

Check here for reference jQuery ajax

Data parameter: Specifies data to be sent to the server.

Try this:

$('#save').on('click touch', function(){
        obj = {
       "1" : {
           "1" : "hey",
           "2" : "hay"
        },              
    "2" : {
        "1" : "hey",
        "2" : "hay"
        }
}

var json = JSON.stringify( obj );

$.ajax({
    data : json,
    type: 'POST',
    url: 'ajax.php',
    success: function(data) {
        alert(data);
        $("p").text(data);
    }
});
});