Append div (loading) when there is no new data

The following AJAX method for a news system:

    function addmsg(msg){
            "<div class='msg'>"+ msg +"</div>"
    function waitForMsg(){
            type: "GET",
            url: "modules/news.php",
            async: true,
            cache: false,
			success: function(data){
				if(data) { 
                } else {
                    setTimeout(waitForMsg, 1000);
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");


What I am looking for is to append a loading div (preferably with a loading image to div news when there are no new news items. Is it easy to implement something like that in the structure as it is now or should I make adjustments?

I tried something by adding the following to the very top of the script:

var loader = jQuery('<div id="loader"><img src="images/loading.gif" alt="loading..." /></div>').hide();

and added this to the else statement along with the setTimeout(waitForMsg, 1000);:;

But that didn’t give me the desired results

this if…else block only runs when the success function is called (i.e. if you have a response). since you want to immediately show the loader, call it before you start the AJAX call.