Nitish
Nitish

Reputation: 2763

Unable to print JSON response in HTML page AJAX

I have a AJAX function as below:

function ajx(){
var ajaxRequest;  // The variable that makes Ajax possible!


try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
       // alert(ajaxRequest.readyState);
    if(ajaxRequest.readyState == 4){
                    //alert(ajaxRequest.responseText);

                    var res = ajaxRequest.responseText;


                    var a = JSON.parse(res);


                    var v1 = a[0];
                    var v2 = a[1];
                    var v3 = a[2];

                    //alert(v1);

                    document.getElementById('vara').value = v1;
                    document.getElementById('varb').value = v2;
                    document.getElementById('varc').value = v3;


    }
}

ajaxRequest.open("GET", "ajax.php", true);
ajaxRequest.send(null); }

the HTML where the id present are :

<div id="vara"></div>
<div id="varb"></div>
<div id="varc"></div>

And the corresponding ajax.php is:

 <?php

$resp = array('man','cow','dog');

echo json_encode($resp);

?>

If I alert v1 v2 or v3 it shows man, cow, and dog respectively. But the it is not printing the values in HTML. Whats wrong?

Upvotes: 0

Views: 1061

Answers (2)

c.P.u1
c.P.u1

Reputation: 17094

document.getElementById('vara') returns an HTMLDivElement, which doesn't have a value property.

You can check this using the construct:

'value' in document.getElementById('vara'); //false

Use the innerHTML property instead, which HTMLDivElement inherits from HTMLElement.

'innerHTML' in document.getElementById('vara'); //true

The value property is only defined for HTMLInputElements (<input type='text' /> etc. )

Upvotes: 0

Jason Goemaat
Jason Goemaat

Reputation: 29194

You're creating a new property on your divs called value because they don't have a value property. You want to set the innerHTML or innerText:

document.getElementById('vara').innerHTML = v1;
document.getElementById('varb').innerHTML = v2;
document.getElementById('varc').innerHTML = v3;

Upvotes: 1

Related Questions