views:

458

answers:

1

Ok,

I need to use ajax for some fancy pop-ups and validation things but I want to avoid javascript redirect if everything is ok in form.

Here is the basic-simple scenario.

We have dynamic site and some user login form. Al logic (does user exist, is password ok etc) is on a server side.

Server pseudo code look like this:

$username,$password; //form user input

if (authenicate($user,$password)){
   redirect('myaccount');
}
else {
   print 'Wrong username and/or password'; //this should be displayed in the popup.
}

Now if I use ajax to display what server printed, how to tell to frontend to leave redirections to server side!?

I solved this on stupid way (because I have about 15 different forms). And I use javascript redirect if answer form server is for example "LOGGED".

Just to mention that I use jQuery and this plugin http://malsup.com/jquery/form/. Some sample code is here: http://pastie.org/584993

I believe that u will understand what I need and I appriciate all suggestions and answers :) Thanks!

+2  A: 

Send back JSON to the client. Have a Status parameter, a Message parameter, and a Url parameter. On success set Status to true, and the Url to the page to which to direct. On error, set status to False and the Message to the error message. On the client side, use the Status to determine whether to redirect or popup the message

 $.ajax({
     url: '/login.php',
     dataType: 'json',
     data: $('form').serialize(),
     type: 'post',
     success: function(data) {
         if (data.Status) {
            location.href = data.Url;
         }
         else {
            alert( data.Message );
         }
     }
 });
tvanfosson