Pure.Krome Pure.Krome - 5 months ago 53
jQuery Question

How can i pass parameters to a JQuery $.getJSON callback method?

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)
});


now the value of
locationType
BEFORE i call the url using Ajax is
3
. But after the Ajax 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.


Hmmm. Ok. so how can i pass 1 or more parameters to a callback method, please?

Answer

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)
});
Comments