2
function submitForm(){
    var urlid = document.getElementById("actionUrl").value;
    jQuery.support.cors = true;

    setTimeout(function(){
      $.ajax({
        url:urlid,
        type : "GET",
        crossDomain : true,
        data:transId,
        success:function(data)
        {
            alert(data);
        },

        error: function (xhr, ajaxOptions, thrownError)
        {
            console.log(thrownError);
            alert(xhr.status);
            alert(ajaxOptions);
            alert(thrownError);
        }
        });
    },1000);
};

I have an ajax call that receives one among the three responses 'true', 'false' or 'pending' from the controller. The ajax should terminate if the response is 'true' or 'false' . If the response is 'pending' the ajax should poll the controller for another 20 seconds. I should be able to pass the response to a different javascript function. Is it possible to do this in ajax/jquery ? I am new to this technology.

munna
  • 43
  • 1
  • 10
  • Did I got i right, that you like to do a request every 20 seconds till the response is true or false? – Karl Adler May 03 '13 at 06:54
  • not exactly. After 20 seconds the ajax call should stop and the url will be redirected to something else. The request should happen for a maximum of 20 seconds or till i get the response as true or false. – munna May 03 '13 at 07:36
  • OK then use the timeout propperty provided by jQuery, which I posted below. – Karl Adler May 03 '13 at 07:38
  • could you provide me a link to an example ? – munna May 03 '13 at 07:41
  • as I posted in answer: http://stackoverflow.com/questions/3543683/jquery-ajax-timeout-setting – Karl Adler May 03 '13 at 07:42
  • when a answer is the right it would be nice when you accept one to mark the problem as solved. Thanks. – Karl Adler May 03 '13 at 08:36

6 Answers6

1

Basically extending Michael's answer

function checkData (data) {
  if (data == 'true')         // do something
  else if (data == 'false')   // do something else
  else if (data == 'pending') {
    if ( !pollServer.stopPoll ) {
      ajaxPoll = setTimeout(pollServer, 1000);
    } else {
      // polled long enough
    }
  }
}

function pollServer() {
  $.ajax({
    url:         pollServer.urlid,
    type:        "GET",
    crossDomain: true,
    data:        transId,
    success:     checkData
    error:       // error function
  });
}

function submitForm(){
  var urlid = document.getElementById("actionUrl").value;
  jQuery.support.cors = true;
  pollServer.urlid = urlid;
  pollServer.stopPoll = false;
  ajaxPoll = setTimeout(pollServer, 1000);
  setTimeout(function() {
    pollServer.stopPoll = true;
  }, 20000);
}
Community
  • 1
  • 1
shyam
  • 9,134
  • 4
  • 29
  • 44
  • This code works fine in all browsers except for IE even though crossDomain is set to true and 'jQuery.support.cors = true' are added. Trying to resolve that issue. – munna May 03 '13 at 11:53
0
var ajaxtimeout = setTimeout(function(){...}

setTimeout(function() { clearTimeout(ajaxtimeout); }, 20000);

Oh, also you'll have to call .abort() on your request object, but I'm too lazy to rewrite your code :)

Ben
  • 54,723
  • 49
  • 178
  • 224
  • I don't think so, those keep firing after each interval, over and over. – Ben May 03 '13 at 06:25
  • @Steve thanks. But i am not able to find a way to stop the ajax once i get the required response. – munna May 03 '13 at 06:35
  • Call `.abort()` on it. This is why I don't use other people's wheels. ;) If you write your own stuff you know what it does lol. – Ben May 03 '13 at 06:36
  • @shyam exactly. Need to poll the server for a value. If the desired response is received, the ajax should terminate. – munna May 03 '13 at 06:37
  • always trying to do that and learning new things too. ajax is interesting. – munna May 03 '13 at 07:46
0

Something like this ought to do it:

function checkData (data) {
  if (data == 'true')         // do something
  else if (data == 'false')   // do something else
  else if (data == 'pending') {
    setTimeout(pollServer, 20000);
  }
}

function pollServer() {
   var urlid = document.getElementById("actionUrl").value;
   $.ajax({
    url:         urlid,
    type:        "GET",
    crossDomain: true,
    data:        transId,
    success:     checkData
    error:       // error function
  });
}

function submitForm(){
   jQuery.support.cors = true;
   pollServer();
}
Michael Teper
  • 4,591
  • 2
  • 32
  • 49
  • I tried using a similar code , but i am getting a 404 Bad request error. My url is correct. – munna May 03 '13 at 07:43
  • What happens if you directly navigate to that URL (put it into the browser address bar)? The code above really wouldn't cause 404 (resource not found) by itself. See if you can debug and get more details about the URL returning 404. – Michael Teper May 03 '13 at 07:46
  • I am able to direct to the url . – munna May 03 '13 at 09:49
  • problem is I think the `urlid` is `undefined` when `pollServer` is called because `urlid` is a variable defined in `submitForm`'s scope – shyam May 03 '13 at 10:16
0

there is a built in jQuery ajax timeout property, please use this: http://api.jquery.com/jQuery.ajax/

timeout
Type: Number
Set a timeout (in milliseconds) for the request.

example here: Determine if $.ajax error is a timeout

Community
  • 1
  • 1
Karl Adler
  • 15,780
  • 10
  • 70
  • 88
0
    function aftersuccess(data)
    {
        if(data=="success"){
            document.getElementById("demo2").innerHTML = data;
            }
        else if(data=="false"){
            document.getElementById("demo2").innerHTML = data; }
        else{
            setTimeout(submitForm,1000);
            document.getElementById("demo2").innerHTML = data;
            }
    }

    var xhr;
    var i = 0;
    var transId; 
    function submitForm(){
        jQuery.support.cors = true;
        var urlid = document.getElementById("actionUrl").value;
        transId = document.getElementById("transId").value;
        transId = 'transId='+transId;

        xhr = $.ajax({
        url:urlid,
        type : "GET",
        crossDomain : true,
        data:transId,
        success:function(data)
        {
            i = i+1;
            aftersuccess(data);
        },
        error: function (xhr, ajaxOptions, thrownError)
        {
            console.log(arguments);
            console.log(xhr.status);
            console.log(ajaxOptions);
            console.log(thrownError);
            alert(xhr.status);
            alert(ajaxOptions);
            alert(thrownError);
        }
        });

        if(i>20){
            xhr.abort();
            alert("Failed :  "+transId)
            window.location.href = "random url";
        }

};

Initialised a variable i . Each time the ajax is called it is incremented. Upon reaching a particular value , i abort the ajax call and redirect the url.

munna
  • 43
  • 1
  • 10
  • `clearTimeout` is for the output of the `setTimeout` not the jQuery ajax variable eg. `var t = setTimeout(...); clearTimeout(t)` – shyam May 03 '13 at 10:14
0

The setTimeOut() method is used to call a JS function after a specified amount of time.As I understand the requirement here is to keep the connection active as long as the response message is "pending".

The codes suggested above will send a new Ajax request if the response message from the server is "pending".

I'll suggest an alternative server side solution to this which worked for me in the past. You will only send back a response if the operation has succeeded or failed and configure a request timeout for that controller say (20 seconds in your case).

Hope this helps.

Arghya
  • 1
  • 1
  • Tried that but not a viable solution.Thanks. As i said , the controller may produce 3 different values as outputs and the ajax should only continue if the response is 'pending'. So can't particularly wait for a single proper response. – munna May 03 '13 at 11:40
  • But the code you are trying will send another Ajax request after 20 seconds if the response is 'pending'. Is that what you want? – Arghya May 04 '13 at 04:42
  • no. The code should be able to abort ajax request after 20 seconds no matter the result. – munna May 06 '13 at 04:46