mahendra kawde
mahendra kawde

Reputation: 847

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?

Upvotes: 2

Views: 4399

Answers (2)

Rayon
Rayon

Reputation: 36609

Try this:

var dom='Your http response';
var wrapper=document.createElement('div');
wrapper.innerHTML=dom;
var elemContainer=wrapper.firstChild;
var elemToFind=elemContainer.querySelectorAll('option');
var facilityselect=document.getElementById('facilityselect');
facilityselect.innerHTML='';
for(var i=0, len=elemToFind.length; i < len; i++){
    facilityselect.appendChild(elemToFind[i]);
}

Creating a fake div element and appending your string which contains a HTML string will help. To insert a DOM object in specific selector, you need to user appendChild method.In case you want to empty the selector and then insert the DOM then set innerHTML as empty (selector.innerHTML="") and then do the append operation.

Upvotes: 1

Barmar
Barmar

Reputation: 780909

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

Upvotes: 6

Related Questions