3

Iam desperately trying to pass a json object using ajax post method to a php file, decode it and pass something back. Php's json_last_error displays 4, which means Syntax error.

this.send = function()
{
    var json = {"name" : "Darth Vader"};
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","php/config.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("data="+json);

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("result").innerHTML=xmlhttp.responseText;
            };
        }; 
    };


<?php   
if(isset($_POST["data"]))
{
    $data = $_POST["data"];
    $res = json_decode($data, true);
    echo $data["name"];
}
?>
2
  • Any reason why you're not using jQuery? Commented Sep 6, 2013 at 1:01
  • 4
    I am totally new to that and I don't want to start all over using a framework I don't understand Commented Sep 6, 2013 at 1:06

1 Answer 1

5

You have to encode it to json if you want to send it as json.

xmlhttp.send("data="+encodeURIComponent(JSON.stringify(json)));

currently what you have will send something like data=[Object object].

The variable json is a JavaScript object which is not json. JSON is a data-interchange format which is basicly a subset of javascript. see http://json.org

var object = {"name" : "Darth Vader"};// a JavaScript object
var json = '{"name" : "Darth Vader"}';// json holds a json string
Sign up to request clarification or add additional context in comments.

2 Comments

You are right, I made an output on that and Object object is what has been transfered before. Your solution works great! Are you able to explain why I have to encode my var json using JSON.stringify, I thought it's json already.
+1 for this answer and question. I just ran into the same problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.