1

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: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
            type: "post",
            data: "email=" + email + "&password=" + password,
            success: function(response) {
                if (response === "1") {
                    window.location.href = "<?php echo Yii::app()->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?

Hammad
  • 1,893
  • 2
  • 16
  • 37
  • A string is just an array of chars. I expect you are iterating a string. Please console.log(response); and edit question with result, plus show your code for //Dispaly response errors above login form – Steve Apr 24 '14 at 14:22

2 Answers2

3

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("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
    email: email,
    password: password
}, 'json');
jqxhr.done(function(response) {
    if (response.valid) {
        window.location.href = "<?php echo Yii::app()->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);
sroes
  • 13,327
  • 1
  • 45
  • 66
  • If you set the correct json header there is no need to use parseJSON. It would be better to always send json as well, not just for errors. Eg `echo json_encode(array('success'=>false, 'errors'=>$model->getErrors());` for failure and `echo json_encode(array('success'=>true, 'errors'=>'');` for success – Steve Apr 24 '14 at 14:27
  • Yes, I agree it's better to always return JSON in this case. This requires you to provide the correct `dataType`. – sroes Apr 24 '14 at 14:31
  • Thank you for all the responses. I think it will solve the problem when I get back to the code in office. Thanks! – Hammad Apr 24 '14 at 16:11
0

In addition to @sroes's answer, use Yii library for JSON

echo CJSON::encode($response);

instead of

echo json_encode($response);

why ?

Why use CJSON encode when we have json_encode

Community
  • 1
  • 1
ramamoorthy_villi
  • 1,630
  • 13
  • 32