Reputation: 163
I can not get my JQUERY .ajax request to accept a function (non-anonymous) to the success condition.
The reason why I am choosing to not use an anonymous function (which I know will work) is because I think they are more difficult to debug and read. I also read that functions should be broken out as a good design and code-reuse factor.
$.ajax({
url: total_url,
type: "POST",
data: {already_voted: already_seen},
success: ajax_get_data_success(data),
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('XHR ERROR ' + XMLHttpRequest.status);
}
My success function is NEVER sent the DATA object?
My error is Uncaught ReferenceError: data is not defined
Obviously data has not been defined, it is supposed to accept the DATA upon success.
Here is my function for the success case:
function ajax_get_data_success(data)
{
try{
console.log(data.id);
console.log("Recieved" + data.id);
update_seen_state(data.id);
update_ui();
}catch(err)
{
console.log("Ajax_get_data", err);
}
}
** Update: As suggested I removed the extra paramaters and the call worked. However, this has sent me through the rabbit hole further as to how calls are made in JQUERY.
**Per the JQUERY API, the success case takes only 3 paramater, and the error case takes 3 paramaters. From a programatic standpoint, that means when a successful ajax connection has been made, their code will pass to MY FUNCTION only 3 paramaters.
Wouldn't Javascript get confused if I increased the number of parameters that were allowed to be passed to the function?
Upvotes: 1
Views: 254
Reputation: 218732
The error is self explanatory. You are using the variable data
which is not defined above. The javascript engine don't know what data
is !
In your case for your ajax success event handler, just specify your function name, no need to specify the param there. Just have it in your function definition (which you already have).
This should work.
success: ajax_get_data_success,
EDIT : As per the comment
What if I wanted to pass it additional arguments?
You can do this
var myArray = ["My","Custom","Array","I want to pass"];
$.ajax({
url: total_url,
type: "POST",
data: {already_voted: already_seen},
success:function (ajaxResponse) { ajax_get_data_success(myArray , ajaxResponse) }
});
and now your method accepts 2 params
function ajax_get_data_success(yourData,ajaxResponseData)
{
console.log(yourData);
console.log(ajaxResponseData);
}
Well, now you are using again an an anonymous method in your success event.
Upvotes: 2