andy4thehuynh
andy4thehuynh

Reputation: 2172

JQuery's AJAX request: what settings are required for retrieving JSON data?

I want to use JQuery's $.ajax request to retrieve some JSON data from a server. I read in JQuery's documentation that all their settings are optional which does not help me understand what I need or do not need. I am unsure what I need. Here is what I have:

JS Code:

function retrieve() {
     $.ajax({
        url : 'some_url',
        type : 'POST',
        dataType: 'JSON',
        contentType : 'application/json',
        data : JSON.stringify({
          key : 'value: ' 
        }),
        error : function(data) {
          console.log('error');
        },
        success : function(data) {
                    // callback function?
        }
     });
}

I want my .retrieve() method to be able to accept a function containing an array of everything on the server like so:

 SomeObject.retrieve(function(array){
       // do something w/ array
 } 

Question: Do I need to omit or add any settings? How do I generate a callback function so that after the messages are downloaded I can use its data? Any replies will be greatly appreciated! Thank you!

Upvotes: 0

Views: 771

Answers (2)

Danwilliger
Danwilliger

Reputation: 1241

Using JQuery's .get() and .post() is easier to understand. Use .get() to retrieve data from your server like so:

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

This is going to get the information from test.html. You need to know the url of where you're getting your data from. This can be a controller on your server. Then the function argument is what happens when it succeeds. here it will populate the result elements html with your data and alert you that the load was performed.

Upvotes: -1

JB Nizet
JB Nizet

Reputation: 691735

To execute something when the AJAX response has been successfully received (in the following example, showing the received data in an alert box):

function retrieve() {
    $.ajax({
        ...,
        success: function(data) {
            alert("Yes! AJAX worked. I received the following data: " + data);
        }
    });
}

To be able to pass a custom success callback function to your retrieve method:

function retrieve(successCallback) {
    $.ajax({
        ...,
        success: successCallback
    });
}

Upvotes: 2

Related Questions