XMLHttpRequest
is an asynchronous request by default, meaning that after you call send
, the next line of code is executed before the request has finished. The code to be executed when the request finished goes into your "state change" handler. You're already assigning a state change handler here:
xmlHttp.onreadystatechange = handleRequestStateChange
But you never define what handleRequestStateChange
actually is. You should probably read about ready states and the onreadystatechange event.
Try the following code instead:
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
This code assigns to handleRequestStateChange
a function which will be called when the ready state of the XMLHttpRequest
changes. The function checks to see if the ready state is 4
(request finished and response is ready) and if so, the you will be able to access the responseText property of the request which will contain the response from the JSP page.
As a suggestion for the future, when you've learned how AJAX request work, you may find a helper library like jQuery makes tasks like this much easier!