Jump to content
Larry Ullman's Book Forums

Problem Accessing Json Data Via Ajax


Recommended Posts

I have set up code to retrieve data from a MySQL database using AJAX. The data is retrieved in JSON format. (Thank you, Larry, for your clear explanations on how to do all this.)

 

Using firebug, I know that the data is returning properly. Here, for example, is what I see in the firebug console when I use the line console.log(JSON.stringify(response, null, 4));
 

[
{
"0": "1",
"1": "Allen",
"2": "Wyatt",
"3": "allen@sharonparq.com",
"4": "8013692885",
"5": "8016072035",
"6": "8013692885",
"7": "238 E. 550 N.",
"8": "",
"9": "Orem",
"10": "UT",
"11": "84057",
"12": "about",
"13": "",
"14": "Awyatt",
"15": "AweEMLr53r/Ds",
"16": "1",
"uid": "1",
"first_name": "Allen",
"last_name": "Wyatt",
"email": "allen@sharonparq.com",
"phone_home": "8013692885",
"phone_work": "8016072035",
"phone_mobile": "8013692885",
"street1": "238 E. 550 N.",
"street2": "",
"city": "Orem",
"state": "UT",
"zip_code": "84057",
"bio": "about",
"picture_file": "",
"username": "Awyatt",
"pword": "AweEMLr53r/Ds",
"super": "1"
}
]

What I don't understand (and what I cannot find in Modern JavaScript) is how to actually use this data. I know how to do this in PHP; it is a piece of cake. (And, perhaps, that PHP knowledge is mucking up my understanding of how to do it in Javascript.)

 

First, I don't understand why my data shows twice in the JSON object. Second, I don't understand the proper Javascript syntax to access the data. For isntance, if I wanted to put together a string that consisted of the first_name field ("Allen"), a space, and the last_name field ("Wyatt") to result in "Allen Wyatt", what is the proper syntax?

 

Quite confused and stumped. Sorry!

 

-Allen

 

Link to comment
Share on other sites

Hello and welcome to the forums.

 

Looking at your output for the response variable, it looks like you have an object within an array (note the curly braces within the square brackets).

 

As such, I would assume that you could access the JS object by typing response[0].

From there, to get "Allen Wyatt", I think the following should work:

response[0].first_name + ' ' + response[0].last_name

That help at all?

If you have any further questions, just ask.

Thanks.

Link to comment
Share on other sites

Thank you. That seems to work.

 

Why, though, are there two sets of my data within the object? The first looks like it is numbered 0 through 16 and the other uses the field names used in the associative array in PHP.

 

-Allen

Link to comment
Share on other sites

The numbered indexes are definitely coming from a (standard) PHP array, and the string indexes are definitely coming from an associative array/object in PHP.

 

I would directly run the PHP script that is echoing the data back out to the JS side, and then try to debug the issue from there.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...