Question

I am trying to directly load a page using ajax. Here are the details:

HTML:

<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>

script.js:

$(document).ready(function() {
    $.ajax({
        url: 'do.php',
        success: function(data){
            $('#feedback').html(data);
    });
});

do.php:

<?php
    //Do whatever...
    echo "Done!";
?>

What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?

Was it helpful?

Solution

As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:

$(document).ready(function() {
    $.ajax({
        url: 'do.php',
        success: function(data){
            $('#feedback').html(data);
    });
});

Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.

I can suggest 2 things:

  1. You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.

  2. Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.

OTHER TIPS

You could start loading immediately and then add the data when everything has completed.

var _data = null;
var _ready = false;

$.ajax({
    url: 'do.php',
    success: function(data){
        _data = data;
        tryAddData();
    }
});

$(document).ready(function() {
    _ready = true;
    tryAddData();
});

function tryAddData(){
     if(_ready && _data !== null){
         $('#feedback').html(_data);
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top