Search code examples
javascripthtmlajaxhtml-parsing

Parse AJAX response in HTML using Javascript


I am using AJAX call in my code using Javascript.

function loadFacility(callback)
{
    //alert('In loadFacility');
    var xmlhttp;
    var keys=document.firstCallInformation.facilityselect.value;
    var urls="http://localhost:8080/webfdms/showFirstCallInformation.do?vitalsId=366";
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status == 200)
        {
             //var some=xmlhttp.responseXML.documentElement;
            var response = xmlhttp.responseText;
            console.log(response)
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET",urls,true);
    xmlhttp.send(null);
}
function loadFacilityCallback(response){
if(response != null){
    //alert(response);
    console.log(response);
    var div = document.createElement("div");
    div.innerHTML = response;
    document.getElementById("facilityselect").innerHTML = div.querySelectorAll("select#facilityselect");;
}

EDIT: I have updated my callback function. But here I received select list as [Object Nodelist]. Now how can I display in my HTML ?

In callback function I received the response as HTML now I want to parse that HTML response so that I can process it further. I am using plain javascript to do so. How to parse ajax response received as HTML?


Solution

  • Create a DIV element and put the HTML in it innerHTML. That will parse it.

    var div = document.createElement("div");
    div.innerHTML = response;
    

    Now you can process it in div, e.g. div.querySelector(".classname"). To get all the <select> tags, do:

    var selects = div.querySelectorAll("select");
    

    To put it into your webpage, you can do:

    document.getElementById("facilityselect").innerHTML = div.querySelector("select#facilityselect").innerHTML