0

I'm trying to access individual elements of my JSON that I've returned from a .post method with jQuery. When I send the data to create.php, all it does is json_encode the data and put it in a json object. Here is my code:

$.post("pages/create.php", {user : "user1", password : "pass2"}, function(data) {
    var newArray = new Array();
    newArray = {"user":"user2","password":"pass2"};
    console.log(newArray.user);
    console.log(data);
    console.log(data.user);

The issue is that the first two console logs do what I would expect. The first one gives me:

"user2"

The second gives me:

"user" : "user1", "password" : "pass2"

But the third is undefined, even though I know the data JSON object has stuff in it. Is my syntax wrong? I'm just trying to access a specific element of that JSON.

mavsman
  • 23
  • 8

2 Answers2

2

Add json as fourth parameter to the $.post() function as

$.post("pages/create.php", {user : "user1", password : "pass2"}, function( data ) {
    console.log( data.user);
}, "json");

This will post to the create.php page and get content which has been returned in json format.

And make sure create.php returns jsonencoded data as:

<?php echo json_encode(array("user1"=>"Kishor","pass1"=>"mypass")); ?>

Also set correct content type HTTP header for JSON as:

header('Content-Type: application/json');

Have a look at jQuery.post() and What is the correct JSON content type?.

Community
  • 1
  • 1
Subedi Kishor
  • 5,638
  • 5
  • 30
  • 51
  • Just to clarify, it tells jQuery that you're expecting a JSON formatted response. It wont actually tell the server what type of response you would like, it's totally up to the server to provide properly formatted JSON. – Wally Lawless Nov 14 '13 at 16:59
  • Yay, the data returned must be jsonencoded, I have mentioned that too. – Subedi Kishor Nov 14 '13 at 17:02
  • And ideally you will have also set the header appropriately on the server side to identify the response type as `application/json`. – Wally Lawless Nov 14 '13 at 17:04
  • Awesome, unfortunately I can't try this out until I get back to work on Monday but I will give it a shot then and it should work. If not, I'll report my findings here. – mavsman Nov 14 '13 at 18:40
0

all answers given seem to be correct, i just have the feeling your JSON response might be missing the "{" and "}" .. but is just returning the properties of the object...

Gekkie
  • 976
  • 9
  • 24