Page 1 of 1

Ajax problems - does it lie in the javascript or the php?

Posted: Sun Dec 06, 2009 9:08 pm
by DrPL
Hi,
I'm experimenting with Ajax and am trying to set up a simple form which will acknowledge which
drop-down box item has been selected. Nothing too drastic I think you'll agree, except that it doesn't work; can anyone see why?

The client side code is here:

Code: Select all

<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
 
function testResults()
{
//var selected_item = document.getElementById('mydropowntest').value;
 
var x=document.getElementById("mydropowntest");
//alert(x.selectedIndex);  // OK, this works
var selected_item = x.options[x.selectedIndex].text;
//alert(selected_item); // OK, this works
 
var selected_distance=document.getElementById('distance').value;
 
document.getElementById('form_data').innerHTML=selected_item;
document.getElementById('distance_data').innerHTML=selected_distance;
 
var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
  {
  document.getElementById('user_data').value=xmlhttp.responseText;
  }
}
var sendurl = 'return_value.php?selected='+selected_item+'?distance='+selected_distance;
//alert( sendurl );
xmlhttp.open("GET",sendurl,true);
xmlhttp.send(null);
 
}
 
</SCRIPT>
</head>
<body>
 
<form name="myform">
<select id="mydropowntest">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<input id="distance" type="text" size="5" value="">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults()">
</form>
 
<div id="form_data"></div>
<div id="distance_data"></div>
<div id="user_data"></div>
 
</body>
</html>
The url to send to the server is being contructed correctly ('return_value.php?selected=Two&distance=5' for instance), and the javascript updates the test divs correctly.

The server side code () is

Code: Select all

<?php
 
$sel = $_GET['selected'];
$dist = $_GET['distance'];
 
var $output;
 
if ($sel=='One')
{
$output = sprintf("One clicked");
}
elseif ($value=='Two')
{
$output = sprintf("Two clicked");
}
else
{
$output = sprintf("Three clicked");
}
 
// distance variable is not being used at present..
 
echo $output;
 
?>
From a test of the code, it looks like the server side code is not being called, but I can't see why. Can any kind soul please help?