Basically what I'm trying to do is returning the results of a mysql query. I know how to put each row of the query results into its own JSON object, now I'm just struggling with a way so that if there's multiple lines of results to return it to my jquery. In my jquery I call the $.ajax() function and I don't have any issues with that. My problem lies within the success part, where I want to be able to do something like the following:
$.ajax ({
type: "POST",
url:"select.php",
data: {columns : "*",
table : "tbUsers",
conditions : "" },
success: function(results) {
foreach (results as obj)
{
JSON.parse(obj);
$("#page").html(obj.id + " " + obj.name);
}
}
});
I want to be able to iterate through the result variable like an array of JSON objects. The results variable is a string that consists of All the output of the php file. So let my question rather then be, how can I change it so that the function gets an array or how do I change it into one?
My php file currently returns something like this:
[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]
From the php
you can use
echo json_encode($result); // result may contain multiple rows
In your success
callback you can use
success: function(results) {
var htmlStr = '';
$.each(results, function(k, v){
htmlStr += v.id + ' ' + v.name + '<br />';
});
$("#page").html(htmlStr);
}
A Demo to help you understand.
Try something like:
$.ajax ({
type: "POST",
url:"select.php",
data: {columns : "*",
table : "tbUsers",
conditions : "" },
dataType: "json",
success: function(results) {
for( var i in results) {
$("#page").html(results[i].id + " " + results[i].name);
}
}
});
Note the dataType: "json" - This will parse it all into a JSON object(s) for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With