I have some variables that I would like to pass into an AJAX call:
e.g.
var moo = "cow noise";
$.ajax({
type: "POST",
url: "",
data: "",
success: function(data){
//return the variable here
alert(moo);
}
});
However, moo comes back undefined.
note, I’ve left url and data empty on purpose – they are populated in my code.
I guess your code might have been wrapped in
$(function(){ ... });as an jQuery thing. removevarwill make it basicallywindow.moo = "cow noise";Which works, but pollutes the namespaces which is not what you want.Do not try to pollute the global namespace, it will make your other code hard to debug.
Use closure which should solve your issue: