Pregunta

I've been trying for about a day now to get this method to work.

I'm trying to use the jQuery .each() function to perform an action for each element in a given array.

The array comes from a .post() request

$(document).ready(function() {
$.post("assets/scripts/chat/load_convos.php",{}, function(data) {

//perform the .each() function

});

})

The array is returned in this format [56,98.24,46] through the php file load_convos.php

This is the PHP file

$get_convos = mysql_query("SELECT status, partner_user_id FROM chat_convos WHERE user_id = '$user_id'");
$following_user_id = '';
$uids = array();
while($row = mysql_fetch_assoc($get_convos)){
    array_push($uids, $row['partner_user_id']);
}
$following_user_id = implode(',', $uids);
echo "[$following_user_id]";

I honestly don't see what I'm doing wrong...

========EDIT==========

This is what I have done so far

$.each(data, function(value) { 
  alert(value); 
});
¿Fue útil?

Solución

change the two last rows of your php script to

 echo json_encode($uids);

and in the jQuery - instead of trying to use $.each, use a regular for loop over the data that you received (you may also want to add a fourth parameter to the $.post to ensure that it handles the response as JSON)

 $(document).ready(function() {
    $.post("assets/scripts/chat/load_convos.php",{}, function(data) {
       for(var i in data){
         //console.log(i+":"+data[i]);
         alert(data[i]);
       }
    },"json");
 })

Otros consejos

You do not have to make changes in your PHP code as per Yaron's suggestion. You can change your jquery code a little bit:

$.each(data, function(index, value) {
   alert(value);
});

See it in action here. http://jsfiddle.net/2KZvt/1/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top