I’m getting undefined for some reason when I try to return the html via the callback function:
function getDataFromUrl(urlWithContent)
{
// jQuery async request
$.ajax(
{
url: urlWithContent,
dataType: "html",
success: function(data) {
return $('.result').html(data);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
I know I’m getting data back, I see it in firebug in the response and also when I alert out the data, I see the entire page content come up in the alert box.
When I call my function, I am doing the following:
var divContent = getDataFromUrl(dialogDiv.attr("href"));
if(divContent)
dialogDiv.innerHTML = divContent;
when I alert out the divContent (before the if statement) I’m getting undefined. Maybe I’m just going about this wrong on how I’m returning back the data?
I also tried just return data; same thing, I get undefined after the call to this method when set to my variable.
Updated per responses:
Tried this, still getting undefined:
function getDataFromUrl(urlWithContent, divToUpdate)
{
$.ajax(
{
url: urlWithContent,
aSync: false,
dataType: "html",
success: function(data) {
divToUpdate.innerHTML = data;
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
I called it from within another function like this:
var divContent = "";
if (dialogDiv.attr("href"))
{
getDataFromUrl(dialogDiv.attr("href"), divContent);
}
You cannot return data from the callback – because there’s no guarantee that the data will have been returned back from the function at the time the function exits (as it’s an asynchronous call.)
What you have to do is update the content within the callback, like:
where your dialog
DIVhasid="dialogDiv"attached to it.I think you can also modify your function to take the object to update when the call completes like so:
Then call it like so (where
dialogDivis the object representing theDIVto update like in your example.)