1

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.

5
  • 2
    You have not set the data attribute on $.ajax options. Commented Jan 13, 2016 at 20:39
  • POST data will be available in the $_POST variable in PHP Commented Jan 13, 2016 at 20:42
  • @csum: only if OP actually bothers to tell jquery to USE that json var in the ajax call... Commented Jan 13, 2016 at 20:46
  • @MarcB yup, true. It was more of a general statement. POST data is in $_POST Commented Jan 13, 2016 at 21:05
  • I have fixed the issue. Thank you all Commented Jan 13, 2016 at 21:27

5 Answers 5

6

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);
Sign up to request clarification or add additional context in comments.

8 Comments

Can you explain the reason behind the 2nd option not being a valid form-urlencoded input? Is it due to the contents of the json variable? The keys being numeric?
form-urlencoded values are in the form param1=value1&param2=value2&param3=value3...
Basically, it's a query string.
So then wrapping your var in {json: ___ } solves this?
Solves because jQuery will automatically convert any object into a form-urlencoded string. Might not work in other Ajax libs.
|
2

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);
    }
});

6 Comments

Thats half the problem
In addition, OP should assing $json = $_POST['json'] unless OP has register_globals=On
don't forget the comma after json
@HenriqueBarcelos: uh, php has no idea what json is. a json string is just a plain text string to php. php expects key=value pairs in POST, value by itself is utterly meaningless. register_globals never did, and never will,decode json...
I meant this part: $obj = json_decode($json). If register_globals=On and the data is passed under the 'json' key, like json={"foo":"bar"}, it would work.
|
0

You have to send the obj with the ajax request

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

2 Comments

dataType refers to the expected response, no the request.
@HenriqueBarcelos in the comment is says 'for json response'
0

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);
    }
});
});

1 Comment

dataType refers to the expected response, no the request.
0

Replace your ajax code with this.

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

For ajax php

<?php 
    $obj = json_decode($_POST['data']);
    echo $obj;
?> 

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.