creating a container in a container with XMLHttpRequest

2 answers

I would like to create a div-container in a div-container using AJAX and afterwards write "Hello World" in the inner container. The outer container has no special function. It just holds the inner container. This is my code:

inex.html:

<!DOCTYPE html> <html>      <head><meta charset="UTF-8"></head>      <body>          <div id="outerContainer"></div>        // this is my outer container          <script>             function request(){                 var req = new XMLHttpRequest();                 req.open("get", "response.php", true);                 req.onreadystatechange=function(){                     if(this.readyState == 4 && this.status == 200)                         document.getElementById('outerContainer').innerHTML = this.responseText;                  };                 req.send();             }                         request();              // write "Hello World" in the inner container             document.getElementById('innerContainer').innerHTML = "Hello World";         </script>      </body>  </html>  

response.php

<?php echo "<div id='innerContainer'>default text</div>";      // put this container inside the outer container ?> 

After running the program I can see in the DOM that the inner div-container was created correctly inside the outer div-container and that it's ID is 'innerContainer'. But writing "Hello World" in the inner container as I tried it doesn't work. Instead it's content is still 'default text'. The console outputs: "index.html:21 Uncaught TypeError: Cannot set property 'innerHTML' of null".

I would appreciate any suggestion or help.

All answers to this question, which has the identifier 61229018

The best answer:

I have tried what I said in my comment and this works.

When you are running document.getElementById('innerContainer').innerHTML = "Hello World"; in your code, this element likely does not exist (hence the 'null' error). You have to remember that you are making an asynchronous request. As such, other parts of the code will execute while the request is made.

One solution is to move the 'hello text' inside the response. So this works:

<!DOCTYPE html> <html>      <head><meta charset="UTF-8"></head>      <body>          <div id="outerContainer"></div>          <script>             function request(){                 var req = new XMLHttpRequest();                 req.open("get", "random.php", true);                 req.onreadystatechange=function(){                     if(this.readyState == 4 && this.status == 200)                         document.getElementById('outerContainer').innerHTML = this.responseText;                          document.getElementById('innerContainer').innerHTML = "Hello World";                 };                 req.send();             }             request();          </script>      </body>  </html>  

As you can see, the Hello World only is then inserted once the element actually exists. No chance of a non-existent div then.

<head><meta charset="UTF-8"></head>  <body>      <div id="outerContainer"></div>        // this is my outer container      <script>         function request(){             var req = new XMLHttpRequest();             req.open("get", "response.php", true);             req.onreadystatechange=function(){               if(this.readyState == 4 && this.status == 200)                   document.getElementById('outerContainer').innerHTML = this.responseText;                     // write "Hello World" in the inner container                   document.getElementById('innerContainer').innerHTML = "Hello World";               };             req.send();         }                     request();       </script>  </body> 

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data