-4

I'm new to using JQuery, and I'm having a problem with this line of code.

function getById(id, callback) 
{
  return  $.get(url, {}, callback);
}

When i look at what .get returns it's not an xml node or JSON which is what I thought it was supposed to return. Instead I get an Object with a collection of Methods and Prototype. Also it has a ready state. So its not returning undefined but its also not returning what I'd expect. what could the problem be?

I've tried assigning the get to a variable but that didn't do anything I also tried using a callback function but I don't really understand how I can use that to assign the data returned from get to a variable.

  • 2
    Short answer: The "A" in AJAX stands for "asynchronous." This means that the `.get()` function *returns* before the AJAX call *completes*. The result of the AJAX call will be available in the `callback` function. Long answer: The question has been duplicated *many times*. See the referenced question above. – David Nov 01 '13 at 13:45

3 Answers3

1

The $.ajax() functions return a jqXHR object. The data returned from the ajax call will be passed to your callback, or to the done callback of the jqXHR object.

I would recommend reading the $.ajax() documentation and the ajax category of the learning site.

Jason P
  • 26,984
  • 3
  • 31
  • 45
0

This is called a promise.

It allows you to use the eventual result of the asynchronous operation.
Call the then() method and pass a callback to run code when the response arrives.
This returns a new promise of the result of that code.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • so in this example, from getByID response, you can call then? var test = getByID(1); test.then( function(res){ console.log(res) } ) – uptownhr Nov 01 '13 at 13:46
0

It return XMLHttpRequest. As AJAX is asynchronous you can't just return $.get method.

So you need to use your callback method:

$.get(url, {}, function( data ) {
    console.log( 'data' );
});
antyrat
  • 27,479
  • 9
  • 75
  • 76