I am trying to build a page that will display the next item in a PHP array when the user clicks on a button. I'm a complete newbie on Ajax, and I am using the "Head First Ajax" book as a guide. My code (below) doesn't work and I don't understand why. Quite frankly, I am not even sure how to debug Ajax...
The code is in a file called Index.php
. I am using WampServer.
The page loads properly. Here is the code:
<html><head><script type="text/javascript">
var id=null;
function getRequest(){
try {
request = new XMLHttpRequest();
}catch (MS){
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (MoreMS){
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (failure){
request = null;
}
}
}
return request;
}
function showNext(itemId){
request=getRequest();
if(request==null){
alert("Request object is null");
return;
}
var url="index.php?itemId="+escape(itemId);
request.open("GET",url,true);
request.onreadystatechange=function(){
if(request.readyState==4){
alert("Request.readyState is 4");
if(request.status==200){
alert("Request.status is 200");
document.getElementById('article').value=request.responseText;
}else{
alert("Request.status not 200");
return;
}
}else{
alert("Request.readystate not 4");
return;
}
}
request.send(null);
}
function getItemId(){
if(id==null){
id=0;
}else{
id=id+1;
}
return id;
}
function doIt(){
itemId=getItemId();
showNext(itemId);
}
</script></head>
<body><p>
<textarea id='article'>
</textarea>
</p>
<p>
<button type="button" id='showNext1' onclick="doIt()" >Show next</button>
</p></body></html>
<?php
$array=array(10,21,32,43,54,65,76);
if(!isset($_GET['itemId'])){
}else{
echo $array[$_GET['itemId']];
}
var_dump("GET :",$_GET);
?>
When I click the button, here is what happens:
I get twice the Request.readystate not 4
alert, then once Request.readyState is 4
, then once Request.status is 200
, then the textarea
gets populated, and then again once Request.readystate not 4
. After all that the textarea
contains my entire code followed by this:
10<pre class='xdebug-var-dump' dir='ltr'><small>string</small> <font color='#cc0000'>'GET :'</font> <i>(length=5)</i>
</pre><pre class='xdebug-var-dump' dir='ltr'>
<b>array</b>
'itemId' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'0'</font> <i>(length=1)</i>
</pre>
Then if I click again I get the same alerts and output except that at the end I get 21<pre class='xdebug-var-dump'....
. Next click produce the same except with 32<pre class....
at the end, etc.