Reputation: 12740
How can I loop through this $user array in jQuery? If 'Failure' returned then error should be printed.
Solution here actually prints it but with this output which is wrong: undefinedadmin_1,admin_2,admin_3
Thanks in advance
<?php
$id = $_POST['id'];
if($id == 1)
{
$users['data'] = array(array('name'=> 'admin_1'), array('name'=> 'admin_2'), array('name'=> 'admin_2'));
echo json_encode($users);
}
else
{
$users['data'] = 'Failure';
echo json_encode($users);
}
?>
$.ajax({
type : 'POST',
url : 'list.php',
data : 'id=' + text_id,
dataType : 'json',
success : function(response)
{
//IF not 'Failure', loop through the array and print content into div.success
//IF 'Failure', show div.fail
}
});
Upvotes: 1
Views: 391
Reputation: 2912
if(response.data == 'Failure') {
console.log('error');
return false;
}
for(var i = 0; i < response.data.length; i++) {
if(typeof response.data[i].name != 'undefined') {
console.log(response.data[i].name);
}
}
Upvotes: 1
Reputation: 10598
if ($.isArray(response)) {
//loop through array
} else {
//show error
}
Upvotes: 1