Ryan Tibbetts
Ryan Tibbetts

Reputation: 412

Ajax request what?

So I have a stupid question about this:

$.ajax({
            type: "GET",
            url: `URL`,
            data: DO STUFF WITH WHAT I GOT FROM THE REQUEST???,
        });

In ajax, when I make a get request from a URL, with the data: parameter am I giving a response that is data or is data the data I received from the request?

Upvotes: 0

Views: 33

Answers (2)

Wiredo
Wiredo

Reputation: 220

You can do something with the data in the success part of the ajax call:

$.ajax({
  dataType: 'json',
  url: url,
  data: data,
  success: success
}); 

In this case, a potential success callback would look like this:

function success(data) {
  // do something with data, which is an object
}

or if there is no data to send:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      handleData(data); 
    }
  });
}

Upvotes: 1

David
David

Reputation: 218847

The main thing to understand here is that any AJAX call (any web request really) has two components: A request and a response. The actual $.ajax() function call is sending the request, and a callback function is provided to handle the response.

To illustrate:

$.ajax({
    type: "GET", // request type
    url: "http://www.example.com/someResource", // destination URL
    data: { name: "David", location: "Boston" } // data to send
});

This would make a GET request to the specified URL, sending it the specified data. The response in this case is ignored, since no callback is provided. But you can provide one:

$.ajax({
    type: "GET",
    url: "http://www.example.com/someResource",
    data: { name: "David", location: "Boston" }
}).done(function(response) {
    // handle the response
});

The function which contains "handle the response" will be called by the system when the AJAX response is received from the server. The response variable (or whatever you want to call that variable, the name doesn't matter) will contain whatever the server sent in return. Which could be anything, really.

Upvotes: 1

Related Questions