Search code examples
jqueryajaxdelay

Display data requested by an ajax.load() call once complete, not during the call


My jQuery code (using ajax) request's data from a local php script (pgiproxy.php). This script grabs the desired webpage. I am using the following php function for this:

function grabPage($pageURL) {
  $homepage = file_get_contents($pageURL);
  echo $homepage;
}

I then extract the html code i need from the returned data using jQuery and insert it into a div called #BFX, as follows:

$("#btnNewLoadMethod1").click(function(){
  $('#temp1').load('pgiproxy.php', { data : $("#formdata").serialize(), mode : "graph"} , function() {
    $('#temp').html( $('#temp1').find('center').html() );
    $('#BFX').html( $('#temp').html() );
  });
});

This works fine. I get the html data (which is a gif image) i need displayed on screen in the correct div.

The problem is i can see the html data loading into the div (dependant on network speed), but what I want is to insert the extracted html code into #BFX ONLY when the ajax request has fully completed.

I have tried to use async:false and call $('#BFX').html( $('#temp').html() ); outside the load() function, this had the same effect.


Solution

  • if you mean #temp1 is the div showing, .hide() then .show() it.

    $("#btnNewLoadMethod1").click(function(){
      $('#temp1').load('pgiproxy.php', { data : $("#formdata").serialize(), mode : "graph"} , function() {
        $('#temp').html( $('#temp1').find('center').html() );
        $('#BFX').html( $('#temp').html() );
        // find img tags... then hide it.... when image finished loading, show it..
        $('#BFX').find('img').hide().load(function(){ $(this).show(); /* this function triggers when image finish loading... */})
      })
    });
    

    .load() for images... quick demo

    code reduction maybe this will also work..

    $("#btnNewLoadMethod1").click(function(){
      $('<div>').load('pgiproxy.php', { data : $("#formdata").serialize(), mode : "graph"} , function() {
        $(this).find('center img').appendTo('#BFX');
        // find img tags... then hide it.... when image finished loading, show it..
        $('#BFX').find('img').hide().load(function(){ $(this).show(); /* this function triggers when image finish loading...*/ })
      })
    });
    

    this is much less element usage...