Steven Dropper
Steven Dropper

Reputation: 467

Is it possible to redirect user from jquery loaded php file?

I want the user to be redirected when a php file is loaded through jquery

Example

$(form).submit(function(){
event.preventDefault();
    $("#div").load("phpfile.php");
});

The PHP file contains: header('Location: ...');

but when the php file is loaded,nothing comes up when I add the header there... Otherwise the result is ok and is loaded to the assigned div. Is there any possible way to redirect user from loaded php file? Thanks.

Upvotes: 1

Views: 70

Answers (1)

charlietfl
charlietfl

Reputation: 171700

If you need conditional redirect I would suggest you return a json response:

The various responses would look something like:

{"redirect":false, "html":"success message html", "url": ""}
// OR
{"redirect":true, "html":"", "url": "/new/url"}

Then use $.getJSON instead of load()

$.getJSON('phpfile.php', function(response){
     if(response.redirect){
        window.location = response.url;
      }else{
        $('#div').html(response.html);
      }
}).fail(function(){ alert('Ooops we got a problem'); });

Upvotes: 1

Related Questions