Jump to content

PHP and AJAX


zimmo

Recommended Posts

I have never dealt with ajax before, but someone has kindly sent me code to work with. This is my situation and what I am trying to achieve.

 

I have 2 drop down menus. The first menu is populated with locations taken from the database, they are pulled into the drop down using distinct, to just list all locations in order. Now I need the second menu to populate based on what they select in the first, I have kept it simple for now to get it working. My problem is that I am getting mysql errors, but I think this is due to the way I have this set up.

 

I have 3 files for this, the index page which has the form, an ajax script and finally a php file to process and get the results for the second drop down.

 

Having never done this before I feel I have it wrong, as I am getting errors all the time.

 

My code is below. Please can anyone assist me, really desperate as spent all day trying different things.

 

1: The index page with the form

<?
include("inc/connect.inc");
?>
<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>

<form action ="search_results.html" method=post>



<div id="dropdownregion" class="leftmenu">
<select name="region" style="width: 196px; margin-bottom: 2px;" class="userinput" onchange="postAjax_RequestString('/dropdown/destinations.ajax.regions.php', 'strLocationRefs=' + this.value, 'dropdownregion')">
<?
$sql = "select distinct region from clients ORDER BY region ASC";
$makes_result = mysql_query($sql);

while($row = mysql_fetch_row($makes_result)) {
print("<option value=\"$row[0]\">$row[0]</option>\n");
}
?></select>

<div id="type" class="leftmenu">
	    <select name="type" style="width: 196px; margin-bottom: 2px;" class="userinput">
            <option value="">- Type -</option>
            <? echo "$type_options";?>
	    </select>


</div>
</div>
</form>

</body>
</html>

 

2: The php form that is used to get the results for the second menu

 

<?php
include("inc/connect.inc");

/* $strLocationRefs = numberFormat($_POST["strLocationRefs"], 0); */

$sql = "select * from clients WHERE $region = 'region' ORDER BY type ASC";
$sql_result = mysql_query($sql);

if (mysql_num_rows($sql_result) ==0)
{
echo (" <p>An error Occured</p>\n");
} 
else {
while ($row = mysql_fetch_array($sql_result)){
$bed_and_breakfast	= $row["bed_and_breakfast"];
}
$type_options .= "<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>";
}
echo $type_options;
?>

 

Finally the ajax code

 

//Ajax functionality

function sendHttpRequest(url, reqstr, objx){
http_request = false; 
if(window.XMLHttpRequest){ // Mozilla, Safari, Opera 8.0+, Firefox...
  http_request = new XMLHttpRequest();
  if(http_request.overrideMimeType) {
     // set type accordingly to anticipated content type
     // http_request.overrideMimeType('text/xml');
   http_request.overrideMimeType('text/html');
  }
}else if(window.ActiveXObject){ // IE
  try{
   http_request = new ActiveXObject("Msxml2.XMLHTTP");
  }catch(err){
   try{
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
   }catch(err){}
  }
}
if(!http_request) {
  alert('Cannot create XMLHTTP instance');
}
http_request.onreadystatechange = function(){
  if(http_request.readyState == 4){
   var ajaxDisplay = document.getElementById(objx); ajaxDisplay.innerHTML = http_request.responseText;
  }
}
http_request.open("POST", url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", reqstr.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(reqstr);
}

function postAjax_RequestForm(url, fieldId, objx){
var reqstr = ""; var fieldArr = fieldId.split(",");
for(i=0 ; i < fieldArr.length; i++){
  reqstr += fieldArr[i] + "=" + document.getElementById(fieldArr[i]).value + "&";
}
sendHttpRequest(url, reqstr, objx);
}

function postAjax_RequestFormNames(fObj, url, fieldId, objx){
var reqstr = ""; var fieldArr = fieldId.split(",");
for(i=0 ; i < fieldArr.length; i++){
  objval = eval("document." + fObj + "." + fieldArr[i] + ".value");
  reqstr += fieldArr[i] + "=" + objval + "&";
}
sendHttpRequest(url, reqstr, objx);
}

function postAjax_RequestString(url, reqstr, objx){
sendHttpRequest(url, reqstr, objx);
}

function postAjax_ClearObject(reqstr, objx){
var ajaxDisplay = document.getElementById(objx); ajaxDisplay.innerHTML = '';
}

 

Any help please to get this working.

Link to comment
Share on other sites

is just me or you dont receive the post value ??

 

//old
$sql = "select * from clients WHERE $region = 'region' ORDER BY type ASC";

//new
$variable = $_POST["strLocationRefs"];
$sql = "select * from clients WHERE $region = '" . $variable . "' ORDER BY type ASC";

 

dont forget to sanitize your inputs ;)

 

//edit

by the way i see something that makes me wonder...

are you sure this is what you want??

 

   while ($row = mysql_fetch_array($sql_result)){
   $bed_and_breakfast   = $row["bed_and_breakfast"];
   }
   $type_options .= "<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>";

 

i think it should be like this

   while ($row = mysql_fetch_array($sql_result)){
   $bed_and_breakfast   = $row["bed_and_breakfast"];
   $type_options .= "<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>";
   }

Link to comment
Share on other sites

Dennis I dont know enough yet on ajax to use jquery, but hopefully that will come with experience.

 

Hi Minase

 

Thanks for the reply, I am not getting errors now, so thats a start. I am not sure I have the actual form page set up correct, as now when you select the location it is redirecting but then I completely lose the first menu and the second menu? It just dissapears and leaves a blank page?

Link to comment
Share on other sites

hmm saw some errors in your code

can you post your actual full code to take a look at

 

1 error is that you

              <? echo "$type_options";?>

and the variable type options isn't defined in the file that echo it ;)

i supose you have the php code in separate file right?

Link to comment
Share on other sites

Hi Minase,

 

Here is the index page with the form on, and also the new php code for the form that is pulled in, the ajax code has not changed so wont post that up.

 

1: index page with the form

 

<?
include("inc/connect.inc");
?>
<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>

<form action ="search_results.html" method=post>



<div id="dropdownregion" class="leftmenu">
<select name="region" style="width: 196px; margin-bottom: 2px;" class="userinput" onchange="postAjax_RequestString('/dropdown/destinations.ajax.regions.php', 'strLocationRefs=' + this.value, 'dropdownregion')">
<?
$sql = "select distinct region from clients ORDER BY region ASC";
$makes_result = mysql_query($sql);

while($row = mysql_fetch_row($makes_result)) {
print("<option value=\"$row[0]\">$row[0]</option>\n");
}
?></select>

<div id="type" class="leftmenu">
	    <select name="type" style="width: 196px; margin-bottom: 2px;" class="userinput">
            <option value="">- Type -</option>
            <? echo "$type_options";?>
	    </select>


</div>
</div>
</form>

</body>
</html>

 

The php page with the query etc.

 

<?php
include("inc/connect.inc");

/* $strLocationRefs = numberFormat($_POST["strLocationRefs"], 0); */

$variable = $_POST["strLocationRefs"];
$sql = "select * from clients WHERE region = '" . $variable . "' ";
$sql_result = mysql_query($sql);

while ($row = mysql_fetch_array($sql_result)){
$bed_and_breakfast   = $row["bed_and_breakfast"];
$type_options .= "<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>";
}
echo $type_options;
?>

 

Thanks for your kind help.

Link to comment
Share on other sites

hmm lets see didnt test this but in theory it should work ;)

 

PHP File

 

<?php
if (isset($_POST["request"])) {
include("inc/connect.inc");

$request = $_POST["request"];
   $sql = "select * from clients WHERE $region = '" . $request . "' ORDER BY type ASC";
   $sql_result = mysql_query($sql);
   
   if (mysql_num_rows($sql_result) ==0)
   {
   echo (" <p>An error Occured</p>\n");
   } 
   else {
   while ($row = mysql_fetch_array($sql_result)){
   $bed_and_breakfast   = $row["bed_and_breakfast"];
   $type_options .= "<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>";
   }
}
echo $type_options;
}
?>

 

 

and index page

 

 

<?
include("inc/connect.inc");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example</title>

<script type="text/javascript">
function get_XmlHttp() {
  var xmlHttp = null;

  if(window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  return xmlHttp;
}


function ajaxrequest(tagID,post) {
  var http =  get_XmlHttp();
  var  info = 'request='+post;

  http.open("POST", 'php.php', true); // edit php.php to your actual php file path
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.send(info);

  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      document.getElementById(tagID).innerHTML = http.responseText;
    }
  }
}
</script>
</head>
<body>
   <select name="region" style="width: 196px; margin-bottom: 2px;" class="userinput" onchange="ajaxrequest('select2','this.value')">
<?
   $sql = "select distinct region from clients ORDER BY region ASC";
   $makes_result = mysql_query($sql);

   while($row = mysql_fetch_row($makes_result)) {
   print("<option value=\"$row[0]\">$row[0]</option>\n");
}
?>
   </select>
   
             <select name="type" id="select2" style="width: 196px; margin-bottom: 2px;" class="userinput">
          </select>
	  
</body>
</html>

Link to comment
Share on other sites

Hi Minase.. sorry to take up your time appreciate the help as been stuck on this all day.

 

I have changed it to the actual file path for index.php but it is still not doing anything in the second drop down. I know that a few locations have bed and breakfast, but nothing appearing.

 

Do we still need the actual form to post? Just noticed that has been stripped out.

Link to comment
Share on other sites

no we dont need that,just tested the code and it's working very good here...

try changing php file to

 

<?php
if (isset($_POST["request"])) {
<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>
<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>
<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>
}
?>

do you see the other menu populated??

Link to comment
Share on other sites

Hi Minase,

 

The first menu is fine, it loads around 15 different locations. Now when I select the location it does not populate anything in the second menu, it just stays blank. Just another question which may throw a spanner in the works. What I need after the selections is to still be able to submit the data to query on another page for results.

 

When you say change the php file, is this just at the top section? dont understand using that new code.

Link to comment
Share on other sites

replace entire php file with this code only and see if it does populate ;)

sorry was in a hurry and didnt write last post good,use the code bellow

 

<?php
if (isset($_POST["request"])) {
echo "
<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>
<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>
<option value=\"$bed_and_breakfast\">$bed_and_breakfast</option>
";
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.