guyfromfl Posted February 9, 2011 Share Posted February 9, 2011 I cannot figure this out. I have a php page that searches a database for like results, json_encodes it and returns it to JavaScript. Firebug's console shows all the correct data is being returned from the php file. I cannot, for the life of me, get jQuery to loop through each json element and display them. What am I doing wrong? Here is the jQuery code: // the link to the php file with the search field var url = "test1.php?sendValue=" + $("#txtValue").val(); // Cast the output html var outString = "<h1>Results</h1>"; $.getJSON(url, function(data){ $.each(this, function(index, item){ //alert("DATA::" + this.id); outString += '<div class="post">' + '<h1>' + this.id + '</h1>' + '</div>'; }); }); // Display the output html $("#display").html(outString); All I get is either undefined or null. Firebug says the returned JSON is: [[{"id":"1","name":"Mark"}],{"1":{"id":"2","name":"peter"}},{"2":{"id":"3","name":"mike"}}] Quote Link to comment Share on other sites More sharing options...
requinix Posted February 9, 2011 Share Posted February 9, 2011 jQuery does AJAX asynchronously. The getJSON will return immediately - not after the loop has executed. So when you try to use outString it'll be too soon. Move that bit into the callback function. // the link to the php file with the search field var url = "test1.php?sendValue=" + $("#txtValue").val(); // Cast the output html var outString = "Results"; $.getJSON(url, function(data){ $.each(this, function(index, item){ //alert("DATA::" + this.id); outString += '' + '' + this.id + '' + ''; }); // Display the output html $("#display").html(outString); }); Quote Link to comment Share on other sites More sharing options...
guyfromfl Posted February 9, 2011 Author Share Posted February 9, 2011 Thanks for the input.. I'm devin on localhost so that is one consideration I might not have seen until later. I moved it to the outside of the $.getJSON method. I found the problem I think, here is the new code for any other noobs that run into this: function sendValue(str){ var url = "test1.php?sendValue=" + $("#txtValue").val(); //var url = "text1.php?sendValue="; $.getJSON(url, function(result){ var outString = "<h1>Results</h1>"; $.each(result, function(i, field) { //$("#display").append(field['id'] + ": " + field['name'] + "<br>"); outString += field['id'] + ": " + field['name'] + "<br>"; // alert("g" + outString); }) }); $("#display").html(outString); } Also, you have to cast the JSON data in the php: while ($login = mysql_fetch_assoc($result)){ $json[] =array("id" => $login['id'], "name" => $login['name']); $i++; } header('Content-type: application/json'); echo json_encode($json); I hope this helps someone! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.