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
es back undefined.
note, I've left url
and data
empty on purpose - they are populated in my code.
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
es back undefined.
note, I've left url
and data
empty on purpose - they are populated in my code.
- I can't detect any problem. Please provide the actual code or a working bug. – Exelian Commented Feb 18, 2011 at 14:00
- Please include the actual code. Your current example if perfectly fine. – Aron Rotteveel Commented Feb 18, 2011 at 14:05
- What is the problem .I don't see any error ? – santosh singh Commented Feb 18, 2011 at 14:08
3 Answers
Reset to default 8I guess your code might have been wrapped in $(function(){ ... });
as an jQuery thing. remove var
will make it basically window.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:
var moo = "cow noise";
(function(moo){
$.ajax({
type: "POST",
url: "",
data: "",
success: function(data){
//return the variable here
alert(moo);
}
});
})(moo);
This should work, can't see anything wrong with your code. Live demo.
as long as the variable is defined inside the same function as the $.ajax
-call, you should be able to use moo
inside the success
-callback since it's inside the closure..
However, if the ajax
-call is made elsewhere, you have to ensure that moo
is inside the same scope. This could be done like this:
function thatDefinesTheVariable () {
var moo = 'cow noise';
makeAjaxCall(moo);
}
function makeAjaxCall (moo) {
$.ajax({
type: "POST",
url: "",
data: "",
success: function(data){
//return the variable here
alert(moo);
}
});
}