When sending an XHR request to the same page you might need to take special care with the PHP code that processes the request. For instance, if you have any output generated on the page before the code that handles the request then you would probably wish to discard that output from the response that is sent back to the javascript callback function. Typically to do this I would use ob_clean()
at the beginning of the request handling code and then ensure the response is terminated using exit
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' ){
/*
listen for XMLHttpRequest requests
----------------------------------
By testing for the existence of a particular header in the request
you can ensure that a simple pageload with querystring does not
trigger the id to be displayed.
The ajax function sets the 'X-Requested-With' header and PHP reads this
as 'HTTP_X_REQUESTED_WITH'
*/
if( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] == 'XMLHttpRequest' && !empty( $_GET['id'] ) ) {
/* discard any previous output */
ob_clean();
/* send the response to the javascript client */
header('Content-Type: text/html');
exit( 'Response='.$_GET['id'] );
}
}
?>
<html>
<head>
<title>XHR to same page</title>
</head>
<body>
<div id='msg'></div>
<script>
var id=23;
var xhr = new XMLHttpRequest();
/* Only display the response if the request succeeds */
xhr.onreadystatechange=function(r){
if( xhr.readyState==4 && xhr.status==200 ){
document.getElementById('msg').innerHTML=xhr.response;
}
};
/*
As the request is to the same page you only require the
query part of the url
*/
xhr.open( "GET", "?id="+id, true );
/*
set some typical headers, including the important 'X-Requested-With' header
*/
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send();
</script>
</body>
</html>