5

I'm using the jQuery validation plugin in Laravel 4.2 and want to submit a log in form via Ajax. Everything works well, but when the form is validated and the user is authenticated the form does not redirect to the intended page.

Actually the user is authenticated (because when I refresh, the page goes to the user's profile), but the Redirect::intended('/') does not work when the form is submitted.

This is my jQuery code:

    var validator = $('#login-form').validate({
    rules: {
        email: {
            required: true
        },

        password: {
            required: true
        }
    },

    submitHandler: function(form) {

        $.ajax({
            url: 'login',
            type: 'post',
            cache: false,
            data: $(form).serialize(),
            dataType: 'json',
            success:function(data){
                $('.message').text(data.error);
                $('.message').fadeIn(200);
            }
        });
        $(form).ajaxSubmit();
    }
});

And this is my controller:

class AccountController extends BaseController {

    public function logInForm() {
        return View::make('pages.login');
    }

    public function logIn() {
        $validator = Validator::make(Input::all(),
            array(
                'email'     => 'required|email',
                'password'     => 'required'
            )
        );

        if ($validator->fails()) {
            return Response::json([
                'error' => $validator->errors()->first()
            ]);

        } else {
            $auth = Auth::attempt(array(
                'email'     => Input::get('email'),
                'password'     => Input::get('password')
            ));

            if ($auth) {
                return Redirect::intended('/');

            } else {
                return Response::json([
                    'error' => 'Email or password is wrong.'
                ]);

            }
        }

        return Response::json([
            'error' => 'Sorry, your request could not be proceeded.'
        ]);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bob
  • 169
  • 1
  • 11
  • 1
    you can redirect using javascript , follow this link http://stackoverflow.com/questions/4744751/how-do-i-redirect-with-javascript – valar morghulis Mar 31 '15 at 09:39

1 Answers1

2

You would be better returning the intended location in your response and then having the client perform the redirect.

if ($auth) {
    return Response::json(['redirectUrl' => 'http://domain.com/dash']);
}

And in the client

window.location = response.redirectUrl;
Joe
  • 4,618
  • 3
  • 28
  • 35