?
Solved

time an ajax request

Posted on 2012-04-11
3
Medium Priority
?
471 Views
Last Modified: 2012-04-25
Is there any way to time how long a jquery ajax request has been going on? sometimes searches take too long and it would be nice to add a jquery abort() button if the search takes over, say, 5 seconds. Any way I can do this!

On the other end of the ajax request is a php file that makes a postgresql request.

Much thanks for any ideas!
0
Comment
Question by:hibbsusan
3 Comments
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 1000 total points
ID: 37834311
here is how you can timeout ajax request if it doesn't respond in stipulated time period:-

$.ajax({
    url: "yourphpurl",
    type: "GET",
    dataType: "json",
    timeout: 5000, //5 secs time out
    success: function(response) { alert(response); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("timed out");
        } else {
            alert(t);
        }
    }
});¿

Open in new window

0
 
LVL 23

Accepted Solution

by:
basicinstinct earned 1000 total points
ID: 37836738
The returned object from $.ajax is an XMLHttpRequest object. This object has an "abort" method. Call this method to cancel the request.

So you could do something like this:

(function(){
  var xhr;
  $('#foo').bind('click', function() {
    if(xhr)
    {
      xhr.abort();
      xhr = null;
      $(this).text("Search");
    }
    else
    {
        $(this).text("Cancel");
        xhr = $.ajax({blah blah blah, your request params...});
    }
  });
})();
0
 

Author Comment

by:hibbsusan
ID: 37837476
Ok. That is a really good idea of doing it. I will try that out and post back. Thanks!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month15 days, 14 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question