4

I want to get last ajax call made in my code .

here is my code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js"></script>


<script>
    function getCreateAccount() {
        $.ajax({
             type: "GET",
             url: "/Account/Register/",
             contentType: "application/json; charset=utf-8",
             dataType: "json"
         });
        console.log($.ajax.mostRecentCall.args[0]);
    }

</script>

</head>
<body>

</body>
</html>

but when i see in my console it says "TypeError: $.ajax.mostRecentCall is undefined" .

Thanks,

bart s
  • 5,068
  • 1
  • 34
  • 55
Ancient
  • 3,007
  • 14
  • 55
  • 104

5 Answers5

8

You may register a global ajaxComplete handler that will be invoked every time an AJAX call finishes.

With this, you can emulate something like the Jasmine $.ajax.calls.mostRecentCall() property:

$(document).ajaxComplete(function(ev, jqXHR, settings) {
    $.ajax.mostRecentCall = jqXHR;
});

In this case I'm saving the jqXHR object, rather than the exact set of parameters that was passed to $.ajax.

Note, of course, that this won't be populated immediately after $.ajax is called - it won't be filled until at least one call has finished.

camiblanch
  • 3,866
  • 2
  • 19
  • 31
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • No no no! If you initialise Jasmine properly, and call spyOn($, "ajax") beforehand, then it should work without any hacks! – jackocnr Apr 24 '14 at 18:58
  • 1
    @jackocnr note that the OP said they wanted to get this functionality _without_ using Jasmine. – Alnitak Feb 09 '18 at 00:27
3

I think mostRecentCall function is from Jasmine framework. You must include Jasmine in your code.

mostRecentCall does not exist in jquery!

Sharky
  • 6,154
  • 3
  • 39
  • 72
0

there is no such this like "$.ajax.mostRecentCall" in ajax jquery.

As PSR mentioned you could try to use a flag variable

user23031988
  • 330
  • 2
  • 10
0

Adding an alert before logging will give enough time for the ajax call to be finished.(that should do the trick)

if you don't want any alerts then you can use sleep() method

Chakradhar Vyza
  • 285
  • 4
  • 11
0

There is nothing like

$.ajax.mostRecentCall

in Jquery. That is from Jasmine.js. Unless and until you add reference to Jasmine.js and follow the steps to spy on function, it will give you an error.

You may want to refer the documentation of Jasmin.js. Here's the link that shows how to use it.

Nilesh Thakkar
  • 2,877
  • 1
  • 24
  • 43