Avisek Chakraborty
Avisek Chakraborty

Reputation: 8299

Redirect after Jquery AJAX call giving Error

After doing an AJAX call, am redirecting- using the following code. But, after AJAX completion, it gives Error alert; then its redirecting.

callService($serviceUrl, $serviceName, 'POST');             
//redirecting to nextpage
window.location.href = "nextPage.html";

function callService($serviceUrl, $serviceName, $method) {
  ......

  $.ajax({
    url : $serviceUrl,
    dataType : "json",
    type : $method,
    data : $requestData,
    success : function (data) {
        switch($serviceName) {
            case 'getTopRated':     populateTopRated(data);
                        break;
            case 'GetLatestScoop':  populateLiveScoop(data);
                        break;
            .....
        }
        $.mobile.pageLoading(true);
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error");
        $.mobile.pageLoading(true);
    }
  });

}

Is there a way to resolve it without- modifying the function?

Upvotes: 4

Views: 5091

Answers (1)

ShankarSangoli
ShankarSangoli

Reputation: 69905

Wait until the ajax request complete before you redirect to another page. Since you redirect as soon as calling the service the request aborts and then error handler is triggered due to which you are seeing the alert message from error handler. Move the code to redirect inside ajax success callback it will work.

function callService($serviceUrl, $serviceName, $method) {
  ......

  $.ajax({
    url : $serviceUrl,
    dataType : "json",
    type : $method,
    data : $requestData,
    success : function (data) {
        switch($serviceName) {
            case 'getTopRated':     populateTopRated(data);
                        break;
            case 'GetLatestScoop':  populateLiveScoop(data);
                        break;
            .....


            //redirecting to nextpage
            window.location.href = "nextPage.html";
        }
        $.mobile.pageLoading(true);
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error");
        $.mobile.pageLoading(true);
    }
  });

}

Upvotes: 3

Related Questions