1

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!

1
  • 1
    "because the function load() override the loading message", not quite sure what that means. What happens and what do you expect to happen? Why are you using a synchronous request anyway? Commented Jun 10, 2012 at 17:19

3 Answers 3

1

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'); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

There is no reason for this request to be synchronous anymore, since you are (rightly) no longer attempting to return anything
0

Try this:

function load(url) { return $.ajax({ url: url, type: 'get', dataType: 'html', async: false }).responseText; } 

Comments

0

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; } }); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.