Chris
Chris

Reputation: 6233

How to output content and redirect using ajax and jquery?

I am building a registration form with jquery which should handle the request via Ajax. My code:

$.ajax( 
{ 
    type: "POST", 
    url: "http://www.example.com/register.php", 
    data: $("#register-form").serialize(),
    cache: false,
    success: function(message)
    {   
                    $("#reg_notification").html(message).fadeIn(400);               
    }           
});

Now the register.php should either output an error if for example the email address is not valid and this will be put into the div reg_notification. If no error is made, then the user should be redirected to a "welcome page". But it is important that this page is not allways static, so in other words, I can not use a location.href in the jquery code but want to use

header("Location: http://www.example.com")

in PHP. The problem is that the user wont be redirected but the content of www.example.com will be put inside the div reg_notification.

I found a similar problem here: How to manage a redirect request after a jQuery Ajax call but the difference is that there they are using json which I can not use due to my server and they are also redirecting inside the javascript and not in the php file.

Upvotes: 0

Views: 2255

Answers (1)

komelgman
komelgman

Reputation: 6999

Impossible with header redirection.

Use something like that:

...
success: function(message)
{   
     $("#reg_notification").html(message)
          .fadeIn(400, function() {window.location = "url"});
}

or

success: function(response)
{   
     if (response.success) {
          $("#reg_notification").html(response.message)
               .fadeIn(400, function() {window.location = response.redirectTo; } );
     } else {
          // somethings else
     }
}   

in php:

header("Content-type: application/json");
echo json_encode(array(
    "success" => true,
    "message" => "some message",
    "redirectTo" => "my url"
));

UPDATE header redirect impossible because XMLHttpRequest transparently follows to redirect url for get result. See there

Upvotes: 1

Related Questions