Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  99] [ 2]  / answers: 1 / hits: 56217  / 14 Years ago, sat, august 7, 2010, 12:00:00

I'm trying to use jQuery to call some custom API via Ajax/$.getJSON.



I'm trying to pass a custom value into the Ajax callback method, but that value is not getting passed through and is actually getting overwritten. This is my code:



var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;

$(#loading_status).show();

$.getJSON(url, null, function(results, locationType) {
searchResults(results, locationType)
});


The value of locationType BEFORE I call the URL using AJAX is 3. But after the call returns the data successfully, the value for locationType is now success. This is because the method signature of the callback is:




callback(data, textStatus)A callback
function that is executed if the
request succeeds.




How can I pass 1 or more parameters to a callback method?


More From » jquery

 Answers
33

You don't need to pass it in, just reference the variable you already have, like this:



var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$(#loading_status).show();
$.getJSON(url, null, function(results) {
searchResults(results, locationType)
});


Also there's no need to pass null if you don't have a data object, it's an optional parameter and jQuery checks if the second param is a function or not, so you can just do this:



$.getJSON(url, function(results) {
searchResults(results, locationType)
});

[#95997] Wednesday, August 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;