I want to fire an AJAX request on the click of a button, But I am unable to trigger it on the back-end.
index.php:
<html>
<head>
<script type="text/javascript">
var req = new XMLHttpRequest();
function send1()
{
req.open("GET", "process.php?q=hello", true);
req.send();
alert(req.responseText);
}
</script>
</head>
<button onclick=send1()>send</button>
</html>
process.php:
<?php
$new= $_GET['q'];
echo $new;
?>
This should give me "hello" in an alertbox why it isn't?
The first A in AJAX means "Asynchronous". What you need to do is listen for the readyState to change:
req.open(...);
req.onreadystatechange = function() {
if( this.readyState == 4) {
if( this.status == 200) alert(this.responseText);
else alert("HTTP error "+this.status+" "+this.statusText);
}
};
req.send();