I’m trying to return a string from of function called ‘tjekdet’, but it won’t return anything but undefined. I just need it to return the string, so I can append the result to $(this).
The reason for me to do it this way, is because the request for test2.php takes around 40 seconds, so I’d rather do them one by one instead. But nevermind that.
Does this have something to do with synchronous calls? Or am I just completely missing something really basic?
function tjekdet(name) {
$.get("test2.php", { test: name },
function(data){
// alert(data); returns correctly in the alert
return data;
});
}
jQuery(function($) {
$('.button').live("click",function() {
$(".navn-list").each(function() {
var navn = $(this).text();
var tester = tjekdet(navn);
alert(tester); // returns undefined
});
});
Yes. Well, really it has to do with asynchronous calls. Your
tjekdetfunction will returnundefinedbefore your AJAXgetreturns anything.Put the alert inside the success callback:
You could use
jQuery.ajaxinstead ofjQuery.getand set theasyncoption tofalse, but that’s rarely a good idea and tends to lock up the browser completely until the data has returned.