Thursday, February 1, 2018

php - Convert ajax response array object to javascript array?



I am using ajax to submit a login form in Yii. Here is my ajax function:



$("#login-form").submit(function() {


var email = $("#email").val();
var password = $("#password").val();

$.ajax({
url: "request->baseUrl; ?>/site/validatelogin",
type: "post",
data: "email=" + email + "&password=" + password,
success: function(response) {
if (response === "1") {
window.location.href = "getBaseUrl(true); ?>/dashboard";

}
else
{
//Dispaly response errors above login form
}
},
error: function() {
alert("Could not perform the requested operation due to some error.");
return false;


}
});

});


My PHP controller function is validatelogin as follows:



 $email = $_POST['email'];
$password = $_POST['password'];



$model = new LoginForm();

$model->email = $email;
$model->password = $password;


if ($model->validate() && $model->login()) {
echo "1";

} else {
print_r($model->getErrors());
}


If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.



But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.



I want to display those errors above login form in else part of success function through a loop.




But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:



array('I','n','c','o','r','r'....)


rather than



array([0]=>"Incorrect password")



How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?


Answer



Encode it to JSON.



In your php:



echo json_encode($model->getErrors());



In your js (in the else):



var errors = $.parseJSON(response);


Edit:



In your case it would be better to always return JSON.



Your JS could be changed to:




var jqxhr = $.post("request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {

...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});


Your PHP:




$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...