6

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"}]
8
  • You'd use PHP json_encode function to create a JSON string, and send that back to jQuery, which will automatically parse the string into a javascript object for you if you just set the dataType to JSON! Commented Sep 26, 2013 at 19:30
  • JSON.parse(obj); should be out of the loop and what is the problem in success ? Commented Sep 26, 2013 at 19:30
  • 3
    JavaScript doesn't have foreach loop. Commented Sep 26, 2013 at 19:30
  • 1
    why not send only one big json string instead of multiple smaller ones? Commented Sep 26, 2013 at 19:31
  • 1
    But it doesn't hurt to specify it anyway. If anything it avoids problems with no side effects. By specifying it, if your php fails and returns nothing, it will send your ajax to the error callback rather than success with a string result. Commented Sep 26, 2013 at 19:41

5 Answers 5

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this will solve the problem (php part), basically it is the same thing as I suggested. However it is better not to use success callback as an option. Better chain your callbacks.
@kasperTaeymans in what way is .done better than success:? sure, .done has more uses, but it isn't "better", it's just another way of doing it.
3

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.

4 Comments

"This will parse it all into a javascript object or array for you."
right... but there's no such thing as a JSON object. it's just an object. And, since he's dealing with a sql query, i bet the result is returned as an array of objects, and it isn't suggested to loop over an array with a for in loop.
dataType: "json" is unnecessary if the PHP sets the content-type to application/json. The one advantage is that using dataType means it'll go into the error handler if invalid json was returned, if an error handler was specified.
@Izkata Agreed, but as he was specifically json decoding the result in his example code, I assumed this wasn't the case.
0

quote from your question

I know how to put each row of the query results into its own JSON object

you need to send one big json string instead of multiple smaller ones. You'll not able to loop through the response because it is not a single json string (it are multiple json strings).

also it is better to chain the ajax callbacks because using them as options will be removed from jquery in the future.

$.ajax({
    url: ' your/url ',
    type: 'POST',
    dataType: 'json',
    data: {param1: 'value1'},
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

http://api.jquery.com/jQuery.ajax/

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

6 Comments

If it's an array which has been parsed into JSON and sent, then you should be able to iterate over it.
"as options will be removed from jquery in the future." no they won't. That depreciation notice is for the success error and complete methods, not options.
yes but the question suggests that there are multiple smaller json strings sent to the server.
@kevin: "To prepare your code for their eventual removal" see api.jquery.com/jQuery.ajax
It isn't being removed. Re-read the quote you placed in your answer, it isn't referencing the success: error: and complete: options.
|
0

You can just return one big JSON result. Because each of your JSON objects can be wrapped in another.

The JSON you return would then be an array of objects (whatever they may be)

{ "objects": [(first object), (second object), ... ] }

Then in your success function, you can iterate over each object and update the page:

var obj = JSON.parse(results);
jQuery.each(objs, function(i, obj) {
  $("#page").html(obj.id + " " + obj.name);
});

Comments

0

return Because wrapped success Then in your success function,you can iterate over each object and update the page You can just return one big JSON result.Because each of your JSON objects can be wrapped in another. The JSON you return would then be an array of objects (whatever they may be)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.