0

I made an login function which returns:

return $.ajax({
    type: 'POST',
    url: CHEAPWATCHER.config.domain + 'api/Authenticate',
    data: data
 });

fiddler show that request was successful and I got my token, but chrome throws this kind of exception:

extensions::uncaught_exception_handler:8 Error in event handler for (unknown): TypeError: Cannot read property 'error' of undefined

I tried to debug and found out that my login function's return statement is making this error. Can someone explain why this happening?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Nikas Žalias
  • 1,594
  • 1
  • 23
  • 51

1 Answers1

0

Let's take a look at the documentation for $.ajax():

Returns: jqXHR
...
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

It's important to understand it does not return the data. It cannot, in any case: this is an asynchronous request, so it will actually happen some time after you call ajax(), but the returned value has to be provided immediately.

You absolutely should look at this canonical question on the topic of using data collected by ajax(). It shows how to use success parameter, and explains why asynchronous requests can't be used in a "traditional" return way.

Alternatively, you can do it in the Promise way. The returned object has a function .done(callback) that will call this callback - later, when the request succeeds - with the data.

$.ajax({
  type: 'POST',
  url: CHEAPWATCHER.config.domain + 'api/Authenticate',
  data: data
}).done(function(result) {
  // Do something (but not return!) with the result
});

Again, to hammer it home: there is no possible way to return this value, since it won't actually happen when you submit the request but later, and you can't "wait" for it.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206