I need to convert a JSON object that the php receive from the html form into php variable. I have two forms form1 gives the values and form2 submits them. this is where I give form2 the JSON string value

-html--javascript function-

var myObj = {
    "username" : theUsername,
    "name" : theName,
    "surname" : theSurName,
    "email" : theEmail,
    "password" : thePass,
    "confirmpass" : thePass2,
    "dob" : theDate,
    "gender" : theGender,
    "age" : theAge
};

var jsonstr=JSON.stringify(myObj);
document.forms["form2"]["hide"].value = jsonstr; //form2 gets the whole string

-php- //$jstr = $_REQUEST["hide"];

//$newObj=JSON.parse(jstr);

//$name = $newObj.name;

This is what I tried, but it doesn't work

I used the post method in the html. How do I now convert it back into seperate variables in php ?

share|improve this question
Separate variables? Do you mean: $username, $name, $surname...? – Jose Adrian Aug 17 '11 at 6:34
It's probably a mere wording issue but JSON can never be an object: JSON is a string. That's why there is an stringify() method. – Álvaro G. Vicario Aug 17 '11 at 6:39

2 Answers

Take a look at json_decode

The result of a json_decode is an associative array with the keys and values that were present in your javascript object.

If you don't know how to get the information after you've posted to a PHP script, take a look at the superglobal $_POST. If you're not familiar with that however, I suggest buying a PHP book or read trough some tutorials :)

share|improve this answer

If you want the string index from de JSON send it to a php page

var myObj = {
    "username" : theUsername,
    "name" : theName,
    "surname" : theSurName,
    "email" : theEmail,
    "password" : thePass,
    "confirmpass" : thePass2,
    "dob" : theDate,
    "gender" : theGender,
    "age" : theAge 
}

Then in the PHP Page:

  extract($_POST);

Then you should see your variables $name, $surname, $email...

Source http://php.net/extract

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.