Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return an array/json object containing json objects through an ajax php call?

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"}]
like image 213
wizzkid Avatar asked Dec 12 '22 11:12

wizzkid


2 Answers

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.

like image 85
The Alpha Avatar answered Dec 14 '22 00:12

The Alpha


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.

like image 20
Ricky S Avatar answered Dec 14 '22 00:12

Ricky S