Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So I have two files: index.php and query.php.

The problem is, I don't know how to use the array (msg.d) retrieved by ajax. The output of my array is:

{"s":0,"d":[{"userPostID":"1","userID":"1","postID":"1","choice":"1"},{"userPostI‌​D":"2","userID":"1","postID":"2","choice":"0"},{"userPostID":"3","userID":"1","pos‌​tID":"3","choice":"1"}]}

What I want to do is to loop through the array so that

while (i < array.length){ 
      if (msg.d[i]['choice'] = 1) {
           //do something with msg.d[i]['postID']
      } else if (msg.d[i]['choice'] = 0) {
           //do something else with msg.d[i]['postID']
      }
      i++
}

I've never worked with object arrays before and from what I can gather, what I'm trying to do is rather complicated and I can't figure out the examples I find.

index.php

<script type="text/javascript">
$(document).ready(function() {
// set $checked values

    $.ajax({
        url: 'query.php',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
                console.log(msg);
                },
        error: function (x, e) {
            alert("The call to the server side failed.");
        }
    });
});
</script>

<?php
$data = mysql_query("SELECT * FROM Posts LEFT JOIN userPosts ON Posts.postID = userPosts.postID AND userPosts.userID = $userID") or die(mysql_error());

while($row = mysql_fetch_array( $data )){
?>

query.php

<?php

$query = mysql_query("SELECT * FROM userPosts WHERE userPosts.userID = $userID") or die(mysql_error());

if (mysql_num_rows($query) == 0)
{
echo 'error';
}
else
{

echo json_encode(mysql_fetch_assoc($query));
}
?>

I know, I'm close... There are no errors!

share|improve this question
1  
Just a recommendation, you shouldn't be storing the userID client-side and sending it to the server. Store it in the session and just make the request without the query string. I say this because consider the situation where I load your page up in Dragonfly or (I assume it's possible in) FireBug and change the code to say: var userID = 1234;, now I see user 1234's data. Perhaps I've misunderstood, but you should seriously reconsider this approach if this is production code. –  Richard Marskell - Drackir Nov 1 '11 at 20:44
    
You are absolutely right. I will work around this. –  Sweepster Nov 1 '11 at 23:52
    
Problem fixed. userID is now called on the server side. New problem presented though.. see paragraph below my code in my question. –  Sweepster Nov 2 '11 at 0:07
1  
Are you getting any errors in the console? Also, can you debug in your browser and see if obj is being set properly? –  Richard Marskell - Drackir Nov 2 '11 at 18:25
2  
Try adding console.log(msg);console.log(obj); before the $.each() and see what they return. It's probably not getting parsed correctly or perhaps not being sent properly. –  Richard Marskell - Drackir Nov 3 '11 at 15:46
show 7 more comments

3 Answers

up vote 2 down vote accepted

I think what you want to do is fetch the whole record set into an array and then pass that as JSON to the client. Right now, you only call mysql_fetch_assoc once. Which means you only get the first row.

The way I would set this up is something like so (Note - I haven't tested this code):

query.php

<?php
$query = mysql_query("SELECT * FROM userPosts WHERE userPosts.userID = $userID");

// Return array contents:
// s = Status value, d = Data
// s == 0 -> Success
// s == 1 -> Error
// s == 2 -> No rows returned
$rtrn = array('s' => 1, 'd' => array());
//Check for error
if (mysql_errno() == 0) {
    //Check for no rows returned
    if (mysql_num_rows($query) == 0) {
        $rtrn['s'] = 2;
    } else {
        //Set status value to 0
        $rtrn['s'] = 0;
        //Get all rows from the query
        while($row = mysql_fetch_array($query)){
            //Append row to the data array
            $rtrn['d'][] = $row;
        }
    }
}
//Echo the return array
echo json_encode($rtrn);
?>

index.php (success callback only)

success: function (msg) {
    if (msg.s == 0) {
        //Loop through returned data array using: msg.d
        //For example: msg.d[0] is the first row.
    } else if (msg.s == 2) {
        alert('No rows returned!');
    } else {
        alert('Error!');
    }
},

Basically, what I'm doing here is ensuring that a JSON object is always returned, even during an error. That object has a status part, so you know what happened, and a data part, so you can return information. For the status, zero is always success and one is always an error but you can use other numbers for different outcomes such as no records returned. This allows you to make your application much more robust.

Let me know if any of this isn't working properly since, as I said, I haven't tested it.

share|improve this answer
    
The array is working great! Thing is though that Error! pops up. I think I'm correct in that the value for status is not being set to 0 in query.php. Would it be correct of me to put $rtrn['s'] = 0; just above the while loop? That seems to fix the problem. And finally, if I were to use a value from msg, would the appropriate form be msg[0][choice]? –  Sweepster Nov 4 '11 at 18:29
1  
@Jonathan You are absolutely right. I forgot to add that. I've updated my answer. With regards to getting the data, you can use msg.d[0] to get the first row. After that, I'm not 100% sure if it would be msg.d[0]['colname'] or msg.d[0].colname. It depends on how the MySQL array got JSON'd. If you see something like "d":[{"col1":val,"col2":val2},{"col1":val3,"col2":val4}] (i.e. an array of objects) then you can use the second option (msg.d[0].colname). Personally, I love JSON for this reason, because it makes the code so much more readable and easy to understand. –  Richard Marskell - Drackir Nov 4 '11 at 18:41
    
much appreciated! –  Sweepster Nov 4 '11 at 19:01
    
No problem! Glad to help. –  Richard Marskell - Drackir Nov 4 '11 at 19:06
    
I hate to be a bother... I've determined that the proper format is msg.d[#]['field']. I can't figure out how to loop through the array so that while i < msg.d.length{ if msg.d[i]['choice'] = 1 {do something with msg.d[i]['postID']} else if msg.d[i]['choice'] = 0 {do something else with msg.d[i]['postID']}... I've never worked with object arrays before and from what I can gather, what I'm trying to do is rather complicated and I can't figure out the examples I find. –  Sweepster Nov 5 '11 at 3:16
show 3 more comments

Try something like this:

You need to parse the response on success http://api.jquery.com/jQuery.parseJSON/

and then loop through it http://api.jquery.com/jQuery.each/

$.ajax(
        {
            type: "POST",
            url: 'query.php',
            data: 'userID=' + userID,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                var obj = $.parseJSON(msg);
                    $.each(obj, function(i, val) {
                        alert(JSON.stringify(val));
                    });
            },
            error: function (x, e) {
                alert("The call to the server side failed.");
            }
        });
share|improve this answer
    
I am receiving an error: The call to the server side failed. For query.php Firebug is showing under the POST tab that JSON:There are no child objects but says SOURCE: user=1. query.php is outputting "No userIDYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" –  Sweepster Nov 1 '11 at 14:56
    
If I remove the line contentType: "application/json; charset=utf-8", from yu code, query.php works fine but then the rest of the ajax code doesn't work (says $.parseJSON is not a function). –  Sweepster Nov 1 '11 at 14:58
add comment

I have figured it out!

<script type="text/javascript">
$(document).ready(function() {
// set $checked values

    $.ajax({
        url: 'query.php',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
                if (msg.s == 0) {
                    //Loop through returned data array using: msg.d
                    for (var key in msg.d) {
                        var obj = msg.d[key];
                        for (var prop in obj) {
                            if (prop == "postID"){
                                if (obj['choice'] == 1){
                                //do something with liked posts.
                                } else if (obj['choice'] == 0){
                                //do something with disliked posts.
                                }
                            }
                        }
                    }
                } else if (msg.s == 2) {
                    alert('No rows returned!');
                } else {
                    alert('Error!');
                }
            },
        });
    });
</script>
share|improve this answer
    
who's the one who keeps down voting my posts? This method works, if you know better, share it with the public otherwise quit being a troll! –  Sweepster Nov 6 '11 at 17:35
add comment

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.