Jump to content

Handling Multi-Dimensional arrays with JSON


guyfromfl

Recommended Posts

I am trying to return an associative array from a mysql query in JSON to JS with AJAX.

 

so lets say we have this php:

// Simplified SQL
$result = mysql_query("SELECT id, description FROM table");

// Encode the Associative array from MySQL and return it to ajax
echo json_encode(mysql_fetch_assoc($result));

 

I now want to deal with it in JS:


var response = ajax.responseText;		// Create the response from the query

// Parse the response from JSON
var searchResult = eval('(' + response + ')');

// Create a mock dialog
var msg = "<div id='multipleResultsDialog'><div style='background-color: #0099FF; padding-left: 10px; font-weight: bold'>Multiple Matches</div>";
		msg += "<div style='background-color: #fff; padding: 10px;'>Please select the correct product:<br /><ul>";
		msg += "<li><a href='#'>Add</a></li>";

                        // Go through each of the elements and add them to the list
		for (i=0; i<searchResult.id.length; i++) {
			msg += "<li>"+ searchResult.id[i] + " - " + searchResult.description[i]+"</li>";
		}	

		msg += "</ul>";

                         // fill the div
		document.getElementById('description').innerHTML = msg;

 

All I can get is this:

Multiple Matches

Please select the correct product:

  • Add
  • 4 - Z
  • 4 - e
  • 1 - p

The id from the only returned record is 441 and the description is "Zephyr"

 

The response from the server is:

{"id":"441","stockNum":"512","brand":"PCM","description":"Zephyr CB&Q 1 Drawing Room, 3 double Bedrooms Vista Dome Buffet Lounge Observation #375 Silver Horizon, HO"}

 

Do I need to append the array from each mysql row in php before returning it to js?

 

I am sure I am searching for something that will return 2+ rows

 

Please help!

 

Thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.