ContactEstablished
ContactEstablished

Reputation: 28

jQuery Ajax Call function

I want to be able to call a function from the "on success" region instead of having to place my code in that region. I'll be using the code twice so I'm trying to figure out how to place it outside of the jQuery.ajax() function.

Here is my current code:

$.ajax({
  type: "GET",
  url: "ws/getweather.ashx?zip=" + vZip,
  dataType: "xml",
  success: function (xml) {
  $(xml).find('weather').each(function () {
     // Load New Data
     ...
});
},
  error: function (xml) {
    alert("Unrecognized Region. Please try again.");
  }
});       

So instead of having...

function (xml) {
  $(xml).find('weather').each(function () {
     // Load New Data
     ...
});

I'd like to put the name of another function, and pass the xml to that function. That way I can have other events call the same set of code.

Thanks in advance!

UPDATE===================================================

Thanks to Mike Richards for his timely response. I'm including the exact syntax below because I had to add a few details to make it work...meaning, pass the XML to the other function.

$.ajax({
type: "GET",
url: "ws/getweather.ashx?zip=32751",
dataType: "xml",
success: function (xml){
    weatherize(xml);
},
error: function (xml) {
    alert("Unrecognized Region. Please try again.");
}
});

And then somwhere below, my other function

function weatherize(xml) {
  $(xml).find('weather').each(function () {
// Load New Data
...
})
};

Upvotes: 1

Views: 2117

Answers (1)

Mike Richards
Mike Richards

Reputation: 5667

you can just pass in a function for that parameter :)

success : successFunction,

and then, somehwere else:

function successFunction(data) {
  // Do Something
}

Upvotes: 5

Related Questions