jQuery JSON Passing / Looping Issue

Hi All,

My ajax function passes back the following JSON STRING

[{"Contact":{"first_name":"Jack","last_name":"May"}},{"Contact":{"first_name":"Jane ","last_name":"May"}},{"Contact":{"first_name":"Jack","last_name":"May"}},{"Contact":{"first_name":"Margaret","last_name":"May"}}]

How do I go about looping through the results? This is what I have but it’s not working.


function populateNameOptions(data)
	{
		
		var themessage = 'We already have the following names in the database with the same last name: ';
	  	
		// LOOP THROUGH THE RESULTS
		// ----------------------------------------------------->
		$.each(data.results, function(i,contact){
     		// this is where we do what we want with the results
			themessage += contact.first_name + ' ' + contact.last_name + ', ';
		});
	  	
		$('#nameNotice').html(themessage);
	}

Thanks

The way your JSON array is constructed won’t work with your code because each index in the array has it’s own key aka Contact, see the below code which takes this into account and should work

function populateNameOptions(data) {
    var themessage = 'We already have the following names in the database with the same last name: ';
    
    $.each(data.results, function(i, contact){
        themessage += contact.Contact.first_name + ' ' + contact.Contact.last_name + ', ';
    });
    
    return themessage;
}

Thanks for the update. I actually figured another way of generating the json data so the first and last name were combined making the jQUERY simpler.

It’s because your variable contact actually contains the following object:

{"Contact":{"first_name":"Jack","last_name":"May"}}

[COLOR=#464646]

So to get to the first/last name you’d have to change your themessage concatenation line to:
[/COLOR]

themessage += contact.Contact.first_name + ' ' + contact.Contact.last_name + ', ';

[COLOR=#464646]

The other option is of course to return your result set differently, with an array of contacts, like so:

[/COLOR]

[
    {"first_name": "Jack", "last_name": "May"},
    {"first_name": "Jane ", "last_name": "May"},
    {"first_name": "Jack", "last_name": "May"},
    {"first_name": "Margaret", "last_name": "May"}
];

P.S. I got distracted while writing and saw Chris answered this already :expressionless: