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
    }
});

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);
    }
}
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
}

Comments

Your Answer

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.