So, I have two files: index.php and query.php.
The problem is that I do not know how to use the array (msg.d) obtained by ajax. The output of my array is:
{"s":0,"d":[{"userPostID":"1","userID":"1","postID":"1","choice":"1"},{"userPostID":"2","userID":"1","postID":"2","choice":"0"},{"userPostID":"3","userID":"1","postID":"3","choice":"1"}]}
What I want to do is loop through an 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 have never worked with arrays of objects before and from what I can collect, what I am trying to do is quite difficult, and I cannot understand the examples that 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!