Nauman Bashir
Nauman Bashir

Reputation: 1752

how to redirect the browser during an ajax call (made using jQuery) in php

i am facing a problem of redirecting the site while in an ajax call..

here is what i wanna do :

  1. make an ajax call to the server.
  2. it goes to a certain process, if an error occurs, i should send to the error page, else resume.

now the problem is when in the server side, if i use :

header('Location: error.php');

It doesnt redirect the page, infact it just brings the data of that page (the whole html) to the javascript success function.

The problem is that i have made a generic library both on the javascript side (to call the ajax) and on the server side.

i need to redirect the page through the server side. i tried adding a js code for

 window.location='error.php';

but didnt get any success

Upvotes: 1

Views: 2209

Answers (4)

DevlshOne
DevlshOne

Reputation: 8457

Have you considered using the $.ajaxError() global AJAX event?

$(document).ajaxError(function(event, jqxhr, settings, exception) {
    alert('An AJAX error occurred in script: ' + settings.url);
    console.log(event, jqxhr, settings, exception);
});

In your main JS lib could do the trick and you can add any type of redirect you like.

Here's the official jQuery documentation..

Upvotes: 0

Bart
Bart

Reputation: 27205

If an error occurs, simply echo the url of the errorpage. For example, using JSON:

Server-side:

echo '{error: "error.php"}';

Client-side:

var xhr = $.ajax({ url: "example.php" })
    .success(function() {
        var obj = JSON.parse(xhr.responseText)
        if obj.error {
            window.location = obj.error;
        }
})

Upvotes: 0

Miquel
Miquel

Reputation: 4829

I think you should have an error handler in your ajax lib. In the server you send back either the correct html or an error code in the header plus the URL to redirect to in the body. In the ajax lib the error code in the header will trigger the error handler. In the error handler you can redirect using window.location = 'page_returned_by_server'

Upvotes: 2

Pekka
Pekka

Reputation: 449425

Why not return an error that the Ajax query can understand instead?

if ($error)
 {  header("HTTP/1.1 500 Internal Server Error");
    echo "A database error has occurred. etc.etc.";
    die();
 }

this will trigger the Ajax request's error callback (if in jQuery). The echoed text will be in the response body.

You can also look for a more fitting status code depending on the situation.

Upvotes: 3

Related Questions