1

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
 }
});
asked Mar 6, 2012 at 10:38

2 Answers 2

1
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);
 }
}
answered Mar 6, 2012 at 10:45
Sign up to request clarification or add additional context in comments.

1 Comment

I have to store names in a variable and print it afterwards but result = result+response.data[i].name + ', '; prints it like this: undefinedadmin_1,admin_2,admin_3
1
if ($.isArray(response)) {
 //loop through array
} else {
 //show error
}
answered Mar 6, 2012 at 10:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.