3

I'm developing a web application using javascript / ajax .

The problem is that in my application (a kind of social network) I need to read information about users (posts in a database). To do this I use a PHP dedicated service with the interactions with database. The service returns HTML formatted for the main page.

Now, I use this service with an AJAX call to bring the HTML and injects it into my page. The problem is that when I try to get an element from the injected HTML with javascript:

document.getElementById('commentsArea_xxx').innerHTML=xmlhttp.responseText;

getElementById returns null.

I think the problem is that after the AJAX call the browser does not update the document and so 'commentsArea_xxx' doesn't exist in the document!

How do I fix this problem?

This is my code:

function moreComments(id){
        var footerIcon = document.getElementById('footer');
            footerIcon.innerHTML="<div style='text-align:center;'><img src='images/home_selected.png' onClick='loadHome()'/><img id='cameraButton' src='images/camera.png'/><img src='images/list.png' onClick='loadMyVideo()'/></div>";
            pageOld=pageCurrent;
            pageCurrent=0;
            document.getElementById("ajaxContent").innerHTML="<div id='wrapper' style='top:95px;'><div id='scroller'><ul id='thelist'><li style='text-align:center;'><img src='images/loading.gif' style='text-align:center;'></li></ul></div></div>";
            var xmlhttp;
            if (window.XMLHttpRequest){
                xmlhttp=new XMLHttpRequest();
            }
            else{
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function(){
                if (xmlhttp.readyState==4 && xmlhttp.status==200){
                    document.getElementById("commentsArea_"+id).innerHTML=xmlhttp.responseText;
                    loaded();
                    me();
                    setTimeout(function () {myScroll.refresh();}, 0);
                }
            }
            xmlhttp.open("GET","home_more.php?id="+id,true);
            xmlhttp.send();
    } 
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Alessio Melani
  • 413
  • 3
  • 6
  • 7

3 Answers3

5

This should do it :

$('body').ajaxComplete(function () {
        document.getElementById('commentsArea_xxx').innerHTML=xmlhttp.responseText;
 });

This will be executed after every ajax call.

UPDATE: If you have not added the element to the DOM go through @T.J Crowder's answer.

Monodeep
  • 1,392
  • 1
  • 17
  • 39
4

I think the problem is that after the ajax call does not update the document and so 'commentsArea_xxx' doesn't exist in document!!!

Right. All the ajax call does is bring the data to your code, on the xmlhttp.responseText property. It's up to you to add it to the document. You can do that by setting the innerHTML of an existing element, or by creating elements via document.createElement and appending them to the document via Element#appendChild / Element#insertBefore / etc.

Check out the various DOM specs for details. The HTML5 spec also has some information on this.


FWIW, there's a lot of utility functionality and browser-difference-smoothing available in a good library like jQuery, YUI, Closure, or any of several others. Leveraging the hard work people have put into these libraries lets you focus on writing code for your specific value-add.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The problem is as you state: ... the ajax call does not update the document... Rather, the javascript AFTER the call to retrieve the php file via AJAX occurs before the DOM has a chance to refresh. However, setTimeout() behaves nicely in that it gives the DOM a bit of time to refresh, then you can put any trailing javascript code within a setTimeout function. At least it works with IE 11, FF 28, Chrome 33 and Opera 11. A delay of nine milliseconds works for me. So I suggest you put any javascript that follows the AJAX call inside a setTimeout() function:

setTimeout(function(){
// Your Code here
    var aVariable = document.getElementById("idRenderedFromAJAX");
}, 9);

The other thing is to let xmlhttp.responseText return its value to a javascript variable that is already connected to the DOM prior to making the AJAX call. Then, any HTML that is rendered via the call will be accessible via a refreshed DOM using, say, getElementById from code placed wuthin the setTimeout function. Just a suggestion as this alternative does not require jquery and does not seem to be floating around on the web.

Dan Taylor
  • 79
  • 1
  • 4