Reputation: 1707
I have these functions. My objective is separate the load function to the rest of the script because i want to customize the loading message
function loadContent(url)
{
$('body').html('Loading');
content = load(url);
$('body').html(content);
}
function load(url)
{
var result = null;
var scriptUrl = url;
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
Now, I call the loadContent function:
$(document).ready(function(e) {
loadContent('index.php');
});
The problem is in this line:
content = load(url);
because the function load() override the loading message.
How can I solve this? Thanks guys!
Upvotes: 1
Views: 1814
Reputation: 18233
You can't try and use the data until the ajax event has returned successfully. Try this and see if it helps.
function loadContent (url) {
var content = {};
$('body').ajaxStart(function() {
$(this).html('Loading');
}).ajaxSuccess(function() {
$(this).html(content.key);
}).ajaxError(function() {
$(this).html('Error');
});
load(url, content);
}
function load(url, content)
{
var scriptUrl = url;
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
success: function(data) {
content['key'] = data;
}
});
}
Upvotes: 0
Reputation: 48793
Try this:
function load(url)
{
return $.ajax({
url: url,
type: 'get',
dataType: 'html',
async: false
}).responseText;
}
Upvotes: 0
Reputation: 87073
As you ajax success need some time to make retrieve data from server, so your return will always null i.e undefined. So you need to loadContent within ajax success function.
function beforeLoad(){
$('body').html('Loading');
}
function loadContent(data)
{
$('body').html(data);
}
function load(url)
{
var result = null;
var scriptUrl = url;
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
loadContent(result);
// You can also set result as html without calling a loadContent
$('body').html(data);
}
});
}
$(document).ready(function(e) {
beforeLoad();
load('index.php');
});
Upvotes: 1