Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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"}]
share|improve this question
    
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! – adeneo Sep 26 '13 at 19:30
    
JSON.parse(obj); should be out of the loop and what is the problem in success ? – The Alpha Sep 26 '13 at 19:30
3  
JavaScript doesn't have foreach loop. – Vohuman Sep 26 '13 at 19:30
    
why not send only one big json string instead of multiple smaller ones? – kasper Taeymans Sep 26 '13 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. – Kevin B Sep 26 '13 at 19:41
up vote 4 down vote accepted

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.

share|improve this answer
    
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. – kasper Taeymans Sep 26 '13 at 19:47
    
@kasperTaeymans, Well, thanks but I just answered as depending on OP's code. – The Alpha Sep 26 '13 at 19:49
4  
@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. – Kevin B Sep 26 '13 at 19:50

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.

share|improve this answer
    
"This will parse it all into a javascript object or array for you." – Kevin B Sep 26 '13 at 19:35
    
Edited, sorry that wasn't too clear. – Ricky S Sep 26 '13 at 19:36
1  
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. – Kevin B Sep 26 '13 at 19:37
    
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 Sep 26 '13 at 19:38
    
@Izkata Agreed, but as he was specifically json decoding the result in his example code, I assumed this wasn't the case. – Ricky S Sep 26 '13 at 19:43

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.

share|improve this answer
    
If it's an array which has been parsed into JSON and sent, then you should be able to iterate over it. – Ricky S Sep 26 '13 at 19:38
    
"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. – Kevin B Sep 26 '13 at 19:39
    
yes but the question suggests that there are multiple smaller json strings sent to the server. – kasper Taeymans Sep 26 '13 at 19:40
    
@kevin: "To prepare your code for their eventual removal" see api.jquery.com/jQuery.ajax – kasper Taeymans Sep 26 '13 at 19:41
    
It isn't being removed. Re-read the quote you placed in your answer, it isn't referencing the success: error: and complete: options. – Kevin B Sep 26 '13 at 19:43

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);
});
share|improve this answer

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)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.