devendra devendra - 1 month ago 7
Ajax Question

How to Show AJAX Response into Alert

This is my code which I currently show the response of an AJAX request in the

innerHTML
of an element, but I want to
alert
the response result instead. How can I do that?

function checkforsampleAdded(){
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() {
if (ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('school_name');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}

var status = document.getElementById('teststatus').value;
var tstid = document.getElementById('tstid').value;

ajaxRequest.open("GET", "<?php echo base_url();?>Test/CheckForSampleAdded/" + tstid, true);
ajaxRequest.send();
}

Answer

Apart from checking the readyState, I'd recommend you also check the status to be 200

Here's the updated code

ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
            var ajaxDisplay = document.getElementById('school_name');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
            alert(ajaxRequest.responseText); // alert the data
        }
    }