Rick
Rick

Reputation: 17013

jQuery, passing success data from AJAX to another function?

I'm trying to get the success data from a jquery Ajax call so I can use it elsewhere but for some reason its only accessible within the actual success call, so immeditaly below works but the other doesnt'.. any advice is appreciated

      success: function(data) {
        alert (data)
      }

this doesn't work when I try to pass "data" onto another function

    $.ajax({
      type: 'POST',
      url: 'http://localhost/site1/utilities/ajax_component_call_handler',
      data: {
            component_function: component_function,
            param_array: param_array
            },
            dataType: "json",
      success: function(data) {
        receiver (data)
      }
    });

}

my ajax success is calling this:

function receiver (data) {

    ajax_return = data
alert (ajax_return)
}

Upvotes: 2

Views: 7502

Answers (2)

Justin Force
Justin Force

Reputation: 6342

Don't use data as a variable name. jQuery objects have an object called data already which holds arbitrary data. If you call your variable dat, you should get better results.

See http://api.jquery.com/jQuery.data/

A shorter implementation could be to just say success: receiver with no parameters, and write your receiver signature as

function receiver(data, textStatus, XMLHttpRequest) {
  /* ... */
}

Then data is passed by the jQuery callback.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039548

Have you tried:

$.ajax({
    type: 'POST',
    url: 'http://localhost/site1/utilities/ajax_component_call_handler',
    data: {
        component_function: component_function,
        param_array: param_array
    },
    dataType: 'json',
    success: receiver
});

Or simply use another variable name other than data as it is already used.

Upvotes: 3

Related Questions