Reputation: 45
I can't get the following code to work. Assume that the ajax call works, and msg['username'] is preset to 'john'. I think I am getting confused with how to pass variables to my callback. Edit: I think my main confusion was how to get the 'msg' variable out of Ajax. It looks like Ajax has a 'hard wired' success method which is pretty much compulsory to use if you want to subsequently use the data from the ajax query- and that method is the only one that can access the result of the ajax call. Here's the code:
<script>
$(document).ready(function(){
function freedome(horace){
$.ajax({
url: "RESPONDERdetails.php",
type: "GET",
dataType: "json",
data:{thing:31}
});
horace(msg);
}
function callbacker(msg){
alert("I am callback");
name = msg["username"];
alert(name);
}
freedome(callbacker(msg));
});
</script>
Upvotes: 0
Views: 55
Reputation: 227220
You just want to use freedome(callbacker);
. In JavaScript, functions can be treated like variables. So, all we need to do is pass the function itself as a parameter.
This makes horace
into a function, so that when you do horace(msg);
, callbacker
will be called with msg
as a parameter.
Also, msg
is never declared anywhere in your example and your horace(msg);
will run before the AJAX call is done. You need use the AJAX call's callback here.
$(document).ready(function(){
function freedome(horace){
$.ajax({
url: "RESPONDERdetails.php",
type: "GET",
dataType: "json",
data:{thing:31},
success: function(msg){
horace(msg);
}
});
}
function callbacker(msg){
alert("I am callback");
name = msg["username"];
alert(name);
}
freedome(callbacker);
});
Upvotes: 1