JQuery AJAX how to use an array of objects?

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"},{"userPostI‌​D":"2","userID":"1","postID":"2","choice":"0"},{"userPostID":"3","userID":"1","pos‌​tID":"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!

+4
source share
3 answers

I think you want to fetch the entire set of records into an array, and then pass this as JSON to the client. Right now you are only mysql_fetch_assoc once. This means that you only get the first line.

The way I installed this is something like this ( Note - I have not 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 that the JSON object is always returned even during an error. This object has a status part, so you know what happened, and part of the data so that you can return information. For status, zero always succeeds and there is always an error, but you can use other numbers for different results, for example, no returned records. This allows you to make your application more reliable.

Let me know if any of this does not work properly, because, as I said, I have not tested it.

+2
source

Try something like this:

You need to analyze the response to the success of http://api.jquery.com/jQuery.parseJSON/

and then swipe 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."); } }); 
0
source

I get it!

 <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> 
-1
source

Source: https://habr.com/ru/post/1379076/


All Articles