Maximus S
Maximus S

Reputation: 11095

JQuery: what's the difference between these two $.get() methods?

Server:

def csv_data(request): #mapped to url /csv_data
    with open('my_static_data.csv', 'r') as csv:
        response = HttpResponse(csv.read(), content_type="text/csv")
        response['Content-Disposition'] = 'attachment; filename="data.csv"'
    return response #returns the csv file

Client:

1.

function csv_data() {
  var response = $.get('/csv_data');
  return response;
}

$(function () {
  var my_data = csv_data();
  console.log(my_data); //returns a response object
  console.log(my_data.responseText); //undefined?!
}

2.

$(function () {
  $.get('/csv_data', function(d) {
    console.log(d); // returns csv_data. Why not the same response object?
  });
}

The data returned by Method #2 is what I intended to use. Why is my_data.responseText is undefined, and why do these two methods return different objects?

Upvotes: 0

Views: 84

Answers (4)

Blue Skies
Blue Skies

Reputation: 2975

First one returns a deferred object.

function csv_data() {
   return $.get('/csv_data');
}

csv_data().done(function(my_data) {
    console.log(my_data);
});

Just a different way of managing the callback.

So no matter what, the data is accessed via the callback. Just that in the first example, you can assign it via the returned object, and in the second, it's assigned as an argument to $.get().

Upvotes: 2

Péter
Péter

Reputation: 2181

Because the requests are async by default. In the first case you want to use the result right after the request started. In the second one, you define a callback which is only called after the request is finished.

Upvotes: 0

Alex W
Alex W

Reputation: 38173

From the docs:

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information).

So response in this code, is not the actual data from the AJAX request:

var response = $.get('/csv_data');

Whereas, here, d is the data response from the AJAX request:

$(function () {
  $.get('/csv_data', function(d) {
    console.log(d); // returns csv_data. Why not the same response object?
  });
}

Upvotes: 0

Ry-
Ry-

Reputation: 224857

$.get is not an overloaded jQuery function; it just returns the asynchronous request object back for convenience, and although that object exists, its response has not yet been filled. You still need to use a callback to use the result:

function csv_data(callback) {
  $.get('/csv_data', callback);
}

$(function () {
  csv_data(function(my_data) {
    console.log(my_data); // returns a response object
    console.log(my_data.responseText); // not undefined
  });
});

Upvotes: 2

Related Questions