Solved

Correct javascript syntax to extract jSON array data?

Posted on 2016-08-29
1
72 Views
Last Modified: 2016-08-29
Experts,

I'm using jQuery's $.getJSON() function to pull data from my MySQL db.

I am able to return a proper JSON array via my PHP file but, I can't figure out how to call the data stored in the array?

I'm attempting to place the first and last name found within the jSON array into an input "$('#'+update_value)".

The values being placed into the input show as "undefined undefined".

jQuery Function
//////////////////////////////////////
//FIND EACH SPONSOR OR ALT USER NAME
$.each($(".alt_user, .sponsor"), function(){
	var NUID = $(this).val();
	var update_value = $(this).attr('update_value');
	if(NUID != ''){
		$.getJSON(
			"scripts/find_nuid.php", 
			{
				term:NUID
			}, 
			function(result){
				$('#'+update_value).val(result.first_name+' '+result.last_name);
			}//END FUNCTION
		);
	}//END IF
});

Open in new window


Example JSON array produced from the PHP file:
[{"first_name":"Joe","last_name":"Blow","nuid":"X123456"}]

Open in new window

0
Comment
Question by:evibesmusic
1 Comment
 
LVL 22

Accepted Solution

by:
Kim Walker earned 500 total points
ID: 41775683
JSON is an object, not an array. Your example shows a JSON object embedded in an array. The JSON object is...
{"first_name":"Joe","last_name":"Blow","nuid":"X123456"}

Open in new window

The square brackets on each end are unnecessary. You must remove those square brackets at each end of the returned value in your PHP file for your existing jQuery code to work. Otherwise I would expect the getJSON call to fail because the result is not a properly formatted JSON object.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question