I have a Javascript function that uses jQuery Ajax to fetch response from a Servlet. It works when I use the anonymous function method-
function doAjax() {
$.ajax({
url : 'Authentication',
data : { userName : 'poko' },
success : function(data){
alert(data); //this works
}
});
}
But when I try to pass the response variable to a declared function nothing happens.
function doAjax() {
$.ajax({
url : 'Authentication',
data : { userName : 'poko' },
success : showResult(data) //this doesn't
});
}
function showResult(d) {
alert(d);
}
Firefox debug gives a ReferenceError: data is not defined. Can I actually get the second method to work?
In the second attempt
function doAjax() {
$.ajax({
url : 'Authentication',
data : { userName : 'poko' },
success : showResult(data) //this doesn't
});
}
you are actually executing showResult
and then assigning its result to the success
handler. What success
expects is an anonymous function or a function reference(without passing parameters to it).
What you can do is
function doAjax() {
$.ajax({
url : 'Authentication',
data : { userName : 'poko' },
success : showResult
});
}
and the data
will automatically be passed in as the first parameter to the function referenced.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments