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"},{"userPostID":"2","userID":"1","postID":"2","choice":"0"},{"userPostID":"3","userID":"1","postID":"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!
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:44obj
is being set properly? – Richard Marskell - Drackir Nov 2 '11 at 18:25console.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