views:

136

answers:

2

I've implemented more complex AJAX before with javascript and PHP, but for some reason this refuses to work. This is copied almost directly from the W3 example.

var xmlhttp;
function changeLoc(str)
 {
 xmlhttp=GetXmlHttpObject();
 if (xmlhttp==null)
   {
   alert ("Browser does not support HTTP Request");
   return;
   }
 var url="action.php";
 url=url+"?q="+str;
 url=url+"&sid="+Math.random();
 xmlhttp.onreadystatechange=stateChanged;
 xmlhttp.open("GET",url,true);
 xmlhttp.send(null);
 }

 function stateChanged()
 {
 if (xmlhttp.readyState==4)
 {
  alert(xmlhttp.responseText);
 }
 }

 function GetXmlHttpObject()
 {
 if (window.XMLHttpRequest)
   {
   // code for IE7+, Firefox, Chrome, Opera, Safari
   return new XMLHttpRequest();
   }
 if (window.ActiveXObject)
   {
   // code for IE6, IE5
   return new ActiveXObject("Microsoft.XMLHTTP");
   }
 return null;
 }

And the simple action.php

<?php
 echo 'here'; 
?>

The function changeLoc is called from a link on the html page. It gets into the readyState = 4 condition , but the alert is blank. I know it's something really simple, but I can't find it.

Thank you.

+2  A: 

Use firebug to see if there are any issues(like there are any 404 etc). Also its better to choose a javascript framework like jQuery for AJAX.

Teja Kantamneni
Yes i really like jQuery, but i don't see how it would effect this basic issue.
febs
Have you used firebug to see whether the request is actually going thru or not? Any other input from you will help to pinpoint the issue.
Teja Kantamneni
Well i've tried it locally with XAMPP and hosting it on a server. I have no experience using firebug.
febs
febs, jQuery doesn't *affect* your issue; you're just simply better off using a framework to handle AJAX instead of assembling your own calls. The framework will make it very easy and handle cross-browser incompatibilities as well :)
macek
I see, i've never used jQuery functionality for Ajax, i've simply built it up from the simple example above, I'll give it a shot.
febs
I think i figured it out.
febs
A: 

After seeing some of the suggestions I saw that the call to my php file was never occurring through firebug. The action that was occurring was when I navigated back to my index through the links on my page that call the Ajax functionality. Once i removed the href from my links, the php worked!

Very tricksy, but now I know better

Thank you for your help.

febs