Wasabi
Wasabi

Reputation: 1591

AJAX and DOM function malfunction

attempting to call a method for creating a display container for the

xmlhttp.responseText;//createDisplayElement()

In the following: JS BIN Document

No Errors to the Error console in FF, but the behavior is off, not refreshing the page properly.

Upvotes: 0

Views: 82

Answers (3)

Aravindan R
Aravindan R

Reputation: 3084

I see 2 issues in the code.

  1. obj is not defined properly.
  2. plain text (xmlhttp.responseText) is appended to a p element.

Both of them are corrected below.

Try this,

function makerequest(serverPage, objID)
{

    xmlhttp.open("GET", serverPage);
    xmlhttp.onreadystatechange = function(){

        if(xmlhttp.status == 200 || xmlhttp.readyState == 4){

            createDisplayElement(objID);
        }
    };

    xmlhttp.send(null);
}

function createDisplayElement(objID){
    var obj = document.getElementById(objID);
    var para = document.createElement("p");
    obj.appendChild(para);
    var txtNode = document.createTextNode(xmlhttp.responseText);
    para.appendChild(txtNode);

}

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

This function lacks a reference to obj

function createDisplayElement(){

    var para = document.createElement("p");
    obj.appendChild(para);
    var txt = xmlhttp.responseText;
    para.appendChild(txt);

}

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270609

Looks like obj may be improperly defined in context of the function. Try this instead:

// It is called as:
obj.createDisplayElement(); 


// But the function also uses obj
function createDisplayElement(){

    var para = document.createElement("p");
    this.appendChild(para);
  //^^^^^^  
    var txt = xmlhttp.responseText;
    para.appendChild(txt);
}

Upvotes: 1

Related Questions