1

I would like to get the duration for a certain ajax request using jquery. For instance I am using this script:

$.ajax({
  type: "GET",
  url: "http://localhost/thescript.php",
  success: function(data){
    $("#container").html(data);
  },
  complete: function(jqXHR, textStatus){
    alert("http://localhost/thescript.php took 'n' seconds to load");
  }
});

I would like to be able to know how long this ajax script loaded the url "http://localhost/thescript.php". For instance alert: "http://localhost/thescript.php took 'n' seconds to load".

fabrik
  • 14,094
  • 8
  • 55
  • 71
Christian Noel
  • 305
  • 4
  • 14

3 Answers3

5

You can use the beforeSend() and complete() functions to compare the current timestamps and calculate the difference.

http://api.jquery.com/jQuery.ajax/

Here you can see all callback hooks provided by $.ajax: http://api.jquery.com/jQuery.ajax/#callback-functions

Danilo Bargen
  • 18,626
  • 15
  • 91
  • 127
  • i tried adding the following: beforeSend: function(){ starttime = new Date().getTime(); }, complete: function(jqXHR, textStatus){ endtime = new Date().getTime(); alert((endtime - starttime)+"ms"); } the script i'm running takes around 60s but it displays 5003ms... what seems to be the problem? – Christian Noel Mar 10 '11 at 08:58
  • Is the request really running and loading the script? In case you only want to show the time difference for successful requests, put the endtime in the `success`-callback. – Danilo Bargen Mar 10 '11 at 09:20
5

How 'bout:

var start = new Date().getTime();
$.ajax({
  type: "GET",
  url: "http://localhost/thescript.php",
  success: function(data){
    $("#container").html(data);
  },
  complete: function(jqXHR, textStatus){
    var duration = (new Date().getTime() - start) / 1000;
    alert("http://localhost/thescript.php took '" + duration + "' second(s) to load");
  }
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Briganti: Oh, you saw that? (Blast, I thought I was fast enough.) For some reason I did minutes. I posted the answer, the page refreshed, and I thought...why did you do minutes? And clicked edit within like a second. Hoped no one would notice... ;-) – T.J. Crowder Mar 10 '11 at 08:58
2

something like this:

var start_ts;
$.ajax({
 type: "GET",
 url: "http://localhost/thescript.php",
 beforeSend: function() {
   start_ts = new Date().getTime();
 }
 success: function(data){
  $("#container").html(data);
 },
 complete: function(jqXHR, textStatus){
  var end_ts = new Date().getTime();
  var dif = (end_ts - start_ts) / 1000; /* convert milisec to sec */
  alert("http://localhost/thescript.php took '"+dif+"' seconds to load");
 }
});
BCsongor
  • 869
  • 7
  • 11