I'm trying to populate two dropdown menus with AJAX that also link to a MySQL database. Dropdown 1 = Brand and Dropdown 2 = Model
The only issue I'm having is passing the variable from Dropdown 1 to another page so that a MySQL search can be run.
Here is the AJAX function:
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
// Remove the options from 2nd dropdown list
for(j=document.testform.model.options.length-1;j>=0;j--)
{
document.testform.model.remove(j);
}
for (i=0;i<myarray.data.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].ModelName;
optn.value = myarray.data[i].ModelName; // You can change this to subcategory
document.testform.model.options.add(optn);
}
}
} // end of function stateck
var url="dd.php";
var cat_id=document.getElementById('s1').value;
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
here is the code for the relevant form. This works in generating the First field.
<form name="testform" method='POST' action='mainck.php'>
Name:<input type=text name=fname>
<?php
echo "<br>Select Brand <select name='brand' id='s1' onchange=AjaxFunction();>
<option value=''>Select One</option>";
$sql="SELECT DISTINCT Id, BrandName FROM tbl_brands order by BrandName"; // Query to collect data from table
foreach ($dbo->query($sql) as $row) {
echo "<option value=$row[Id]>$row[BrandName]</option>";
}
?>
</select>
Then it uses a page called dd.php which GETS the variable from first dropdown selection, runs a MySQL query and then outputs information into the second drowpdown.
<?php
@$cat_id=$_GET['Id'];
//$cat_id=2;
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
}
/// end of checking injection attack ////
require "config.php";
$sql="SELECT ModelName FROM tbl_model WHERE tbl_model.Id IN (SELECT DISTINCT ModelId FROM tbl_products WHERE BrandId=$brand)";
$row=$dbo->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result);
echo json_encode($main);
?>
the issue is the page is not getting the variable. If I comment out the @$cat_id=$_GET['Id']; and then replace that with a set variable of $cat_id=2; the whole thing works perfectly.
The Problem: is passing the variables. The main page is not sending the variable to my page dd.php