2

Ok, I'll put my code:

$("#html_contenido").load("../../jsp/comun/contenedor_operativa.html" ,function(){
    $("#html_publicidad_reservar").load("../../html/pub/publicidad_reserva/publicidad_reservar_fr.html", function(){
        alert($("#html_publicidad_reservar").html());
    });
});

alert($("#html_publicidad_reservar").html());

The first alert shows what publicidad_reservar_fr.html() has inside, but the second alert doesn't show it, so in the webpage nothing appears inside #html_publicidad_reservar

Can anyone tell me what's wrong with this code?

2
  • do you have any javascript errors ? Commented Jul 6, 2011 at 16:26
  • yes, but they come from another page Commented Jul 7, 2011 at 7:09

3 Answers 3

3

The second alert executes while the AsynchronousJAX is still running. So the element is still empty. If you need to run code after it has been loaded, do it in your inner callback where the first alert is located.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, ok everybody, but the fact is that it seems that #html_contenido is filled up with the code from the .load() instruction, as seen with the first alert (it throws the code from the .load() ), but when I see the code in the webpage, the code is not loaded. This is the real problem.
If you use "View Source" it shows the initial source, not the modified source. You need to use e.g. Firebug to see the current source.
1

second alert run before the first one because load function make Ajax call then run the its call back function so the scenario is

  1. Load function
  2. second alert
  3. Finish Load
  4. run callback

you can check this

Comments

1

.load uses ajax, which by default is asynchronous, so the first alert shows it AFTER the html loads, while the second alert runs before the first alert and at that time, nothing is .loaded yet.

Timeline is this:

  1. Javascript reads the .load and executes it.
  2. The second alert fires because .load from #1 is still happening
  3. contenedor_operativa.html is loaded.
  4. Since #3 happened and it has loaded, the next .load happens
  5. After the nested .load happens, the first alert in the source code happens

What this means is, that you should put your code inside of where the first alert in the source code is, otherwise you're operating on non-loaded elements.

You can do asynch:false but that kills the whole purpose of using XHR/"Ajax"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.