Populate select menu onChange - javascript

I have a bootstrap select menu which I want to populate onChange from another select menu. I think I have some problems with returning the data from PHP.
Select menu:
<div class="col-md-6" style="width:100%;margin-bottom: 10px;">
<div class="input-group" style="width:100%;">
<span style="width:50%;" class="input-group-addon" id="basic-addon1">Municipality *</span>
<select class="selectpicker" name="object_Municipality" id="object_Municipality">
<option value="0" selected="selected" >Municipality *</option>
</select>
</div>
</div>
Javascript function (called onChange from another select menu) to populate the select menu:
function populate_obcina(value) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("object_Municipality").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_Municipality.php?q="+value,true);
xmlhttp.send();
}
My get_Municipality.php file:
<?php
require_once 'functions.php';
$conn = dbConnect();
$q =($_GET['q']);
$municipality = mysqli_query($conn, "SELECT id,municipality FROM municipalities WHERE `region`='".$q."'") or die(file_put_contents('error_querry.txt', print_r("Error: " . mysqli_error($conn), true)));
while ($row = mysqli_fetch_array($municipality, MYSQLI_ASSOC)) {
$fp = fopen("while_loop.txt", "a") or die("Couldn't open log file for writing.");
fwrite($fp, PHP_EOL .'<option value="'.$row['id'].'">'.$row['municipality'].'</option>');
fflush($fp);
fclose($fp);
//In the while_loop.txt I get lines like this:
//<option value="1">Chicago</option>
//so I guess the problem is the way I am returning the results
echo '<option value="'.$row['id'].'">'.$row['municipality'].'</option>';
}
mysqli_close($conn);
?>
This is the return I get:
<option value="1">Chicago</option><option value="2">LA</option><option value="3">California</option>

I already did that kind of job, but I did it differently since I had to be able to populate many kinds of selects, on events, with pre-chosen data or not, ... with Jquery, bootstrap, & so on...
SELECT HTML :
<div class="col-md-6" style="width:100%;margin-bottom: 10px;">
<div class="input-group" style="width:100%;">
<span style="width:50%;" class="input-group-addon" id="basic-addon1">Municipality *</span>
<select class="selectpicker" name="object_Municipality" id="object_Municipality">
<option value="0" selected="selected" >Municipality *</option>
</select>
</div>
</div>
Javascript/Jquery populate "class", just make a file called PopulateList.js like this :
function PopulateList(){ }
PopulateList.municipality = function(element,choice){
$(document).ready(function(){
$.ajax({
type : 'POST',
url : './getMunicipalitiesChoice.php',
data : {'choice':choice},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
element.html(response);
}
});
});
};
JQuery On change event :
$(document).on('change','#listFiringTheEvent',function(){
//Call the populate function here
populateList.municipality('#object_Municipality',$(this).val());
});
PHP getMunicipalitiesChoice.php :
<?php
require_once 'functions.php';
if(isset($_POST['choice'])){
$conn = dbConnect();
$q = $_POST['choice'];
$result = '';
$municipality = mysqli_query($conn, "SELECT id,municipality FROM municipalities WHERE `region`='".$q."'") or die(file_put_contents('error_querry.txt', print_r("Error: " . mysqli_error($conn), true)));
while ($row = mysqli_fetch_array($municipality, MYSQLI_ASSOC)) {
$fp = fopen("while_loop.txt", "a") or die("Couldn't open log file for writing.");
fwrite($fp, PHP_EOL .'<option value="'.$row['id'].'">'.$row['municipality'].'</option>');
fflush($fp);
fclose($fp);
$result.='<option value="'.$row['id'].'">'.$row['municipality'].'</option>';
}
mysqli_close($conn);
echo json_encode($result);
}else{
//If you're here, that's because the file has been called with a "invalid" choice (not set)
}
?>
Now, as you said, if you have some other lists to fill, just add functions in your PopulateList.js file like this, for example, a function that fills a list with ALL municipalities, not depending on any choice :
PopulateList.municipalities = function(element){
$(document).ready(function(){
$.ajax({
type : 'POST',
url : './getMunicipalities.php',
dataType : 'json',
error : function(response){},
success : function(response){
element.html(response);
}
});
});
};
OR for example you fill a "cities" list when you chose a "municipality" :
PopulateList.citiesOnMunicipality= function(element,municipality){
$(document).ready(function(){
$.ajax({
type : 'POST',
url : './getCitiesOnMunicipality.php',
data : {'municipality':municipality},
dataType : 'json',
error : function(response){},
success : function(response){
element.html(response);
}
});
});
};
In my example here, I assume that your html and php code are "good".
But (for PHP) you have to use prepared statements...
Hope this helps!

Related

How to fetch mutiple values on select option and display in input type using ajax?

I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research

How to get the selected value from dropdown list and past it to sql query

i have two dropdown list box,first one is sales area contain different kind of alphabet which get from cookie,second dropdown staff name is to change according to the selected value from first dropdown. How can i manage to pass the selected option value to my sql query so that it can be change according to the selected sales area.
This is the results that i want to get I insert my code to the snippet for easy to do edit and demonstration.
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("slct2").innerHTML=response;
}
});
<table >
<tr>
<td> Sales Area
<select name="Area" id="area" >
<?php
$sarea = explode(",",$_COOKIE['cooAreaCode']);
foreach($sarea as $item){
?>
<option value="<?php echo strtolower($item); ?>"><?php echo $item; ?></option>
<?php
}
?>
</select >
</td>
<?
$var = $_POST['Area'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$var'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
odbc_free_result($rs);
odbc_close($link);
?>
<td> Staff Name
<select id="slct2">
?>
</select>
</td>
<label class="form_field">Your selected <span id="aggregator_name"></span></label>
(updateleave.php)
if (isset($_POST['get_option'])) {
$item=$_POST['get_option'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$item'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
for($i=0; $i < count($porr);$i++) {
echo "<option value="strtolower($porr[$i]['StaffName']);" >" .$porr[$i]['StaffName']."</option>";
odbc_free_result($rs);
odbc_close($link);
}
?>
Use append to add option tags with in select tag also do all the work in change event of the first drop down ("#area")
$(document).ready(function(){
$("#area").change(function()
{
var val =$(this).val();
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
$("#clct2").append(response);
}
});
});
});
I'm not a fan of jQuery, so you'll need to convert my Javascript to your needs, but what you need is to capture an onchange event for the first drop down and use it to dynamically process the SQL for the second dropdown.
<script>
document.getElementById('area').onclick = function(){
var xmlhttp;
var formData = new FormData();
formData.append('area_value', this.value);
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText); // for DEBUGGING.
if(xmlhttp.responseText == 'false'){
alert(xmlhttp.responseText);
} else {
document.getElementById('slct2').innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("POST", 'build_slct2.php');
xmlhttp.send(formData);
xmlhttp.onerror = function () { console.error(xmlhttp.statusText); }
}
</script>
The build_slct2.php script would use $_POST['area_value'] to create the desired SQL query, process the query, and build the <option></option> list that will end up in the slct2 drop down. The build_slct2.php file would simply echo the new contents for slct2.

Receive post data ajax with php

I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}

How to filter data using an input box and dropdown menus

Hey So I have an issue with my code where I am trying to filter the data coming from the database and display it in a table. I am using AJAX to send the request to the PHP page. I have not had any luck in searching for a solution. (It will be similar to your common real estate website, or retail, etc. where the user can input a location in the search box, search for it, and then filter the displayed data using the 2 dropdown menus).
My index.php page has 3 inputs (a textbox and 2 dropdowns)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off">
<div id="here"></div>
<select class="orderType" name="type" id="orderByType" data-toggle="dropdown" onchange="displaySelection(this.value)">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" id="orderBy" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable">
Then my ajax calls on the index.php page (The AJAX will be another question later, as I'm sure there is a better way than what I have, to send the data)
function fill(Value)
{
$('#search').val(Value);
$('#here').hide();
}
$(document).ready(function(){
$("#search").keyup(function(){
var x = $('#search').val();
if(x==""){
$("#here").html("");
$('#searchTable').html("");
}
else{
$.ajax({
type:'POST',
url:'test.php',
data:'q='+x,
success:function(html){
$("#here").html(html).show();
}
});
}
});
$('.searchForm').change(function(){
var type = $('#search').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { search : type, city : city },
success: function(response){
$("#searchTable").html(response);
$('#search').live("keypress",function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
e.stopPropagation();
$('#searchTable').show();
}
});
}
});
});
$('.orderClass').change(function(){
var order = $('#orderBy').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderBy : order, city : city },
success: function(response){
$("#searchTable").html(response);
}
});
});
$('.orderType').change(function(){
var type = $('#orderByType').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderByType : type, city : city},
success: function(response){
$("#searchTable").html(response);
}
});
});
});
And then on test.php
(I can filter the data with the 2 dropdown menus and that will work fine, but i'm not sure how to filter the data that is displayed from the search input box.)
$stmt = "SELECT * FROM places";
if(isset($_POST['search'])){
$search = htmlspecialchars($_POST['search']);
$stmt .= " WHERE name = :search";
}
if(isset($_POST['orderByType'])){
$selection = $_POST['orderByType'];
$stmt .= " AND type = :selection";
}
if(isset($_POST['orderBy'])){
$order = $_POST['orderBy'];
$selection = $_SESSION['id'];
$stmt .= " ORDER BY".$order;
}
$stmt = $conn->prepare($stmt);
$search = "%".$search."%";
$stmt->bindValue(':search', $search, PDO::PARAM_STR);
$stmt->bindParam(":selection", $selection);
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo $row['data'];
}
}
//Search input live search
if(!empty($_POST['q'])){
$name = $_POST['q'];
$name = htmlspecialchars($name);
$liveSearch = $conn->prepare("SELECT name, city FROM places WHERE name LIKE :name OR city LIKE :name");
$name = "%".$name."%";
$liveSearch->bindValue(':name', $name, PDO::PARAM_STR);
$result = $liveSearch->fetchAll();
if($liveSearch->rowCount() > 0){
foreach($result as $row){
echo $row['name'];
}
}
else{
echo "No results found";
}
}
(If there is a great system in place that can search using user input and then filter it using dropdown menus, then please let me know)
Thanks in advance.
If I was going to do this, I would probably make an ajax object for reuse reasons and a php object to handle queries:
/defines.php
You may or may not have defines for your db credentials. I use these in the class below.
define("DB_USER",'root');
define("DB_PASS",'password');
define("DB_HOST",'localhost');
define("DB_NAME",'dbname');
/classes/Query.php
This is a stripped-down query engine which makes basic queries. I use it to save on rewriting a bunch of prepares and executes, but you can do whatever you like there.
class Query
{
private static $singleton,
$con;
private $rquery,
$bind;
public function __construct()
{
if(self::$singleton instanceof Query)
return self::$singleton;
self::$singleton = $this;
}
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
return self::$con;
}
public function query($sql,$bind = false)
{
$this->bind = false;
try {
if(empty($bind)) {
$this->rquery = $this->connect()->query($sql);
}
else {
foreach($bind as $key => $value) {
$bkey = ":{$key}";
$this->bind[$bkey] = $value;
}
$this->rquery = $this->connect()->prepare($sql);
$this->rquery->execute($this->bind);
}
}
catch (PDOException $e){
die('An application error occurred.');
}
return $this;
}
public function getResults()
{
while($results = $this->rquery->fetch(PDO::FETCH_ASSOC)) {
$row[] = $results;
}
return (!empty($row))? $row : 0;
}
}
/functions/searchPlaces.php
function searchPlaces($search,$type = false,$orderby = false)
{
$sVal = "%".$search."%";
array();
$sql[] = 'SELECT * FROM places WHERE `name` LIKE :0 or `city` LIKE :1';
$bind = array_fill(0,2,$sVal);
if(!empty($type)) {
$bind[] = $type;
$sql[] = 'AND `type` = :2';
}
if(!empty($orderby)) {
$order = ($orderby == 'lowest')? 'ASC' : 'DESC';
$sql[] = "order by `ID` {$order}";
}
// Here is where I use the query to send back results from DB
// you can just use a regular prepare/bind/execute if you like
$qEngine = new Query();
return $qEngine->query(implode(' ',$sql),$bind)->getResults();
}
/test.php
<?php
// Put our db credentials
require_once(__DIR__.'/defines.php');
if(!empty($_POST)) {
// Needs the search function and the query class
// (disregard class if you don't use it)
require_once(__DIR__.'/functions/searchPlaces.php');
require_once(__DIR__.'/classes/Query.php');
// I am just sending an array back, but you can format it as you please
print_r(searchPlaces($_POST['search'],$_POST['type'],$_POST['order']));
exit;
}
/index.php
<script>
// I like to make an ajax engine, it saves on rewriting all the same stuff
// on later ajax calls
var AjaxEngine = function($)
{
this.send = function(data,func)
{
$.ajax({
url: '/test.php',
data: data,
type: 'post',
success: function(response){
func(response);
}
});
return this;
};
}
// You only need one document ready
$(document).ready(function(){
// Make an ajax engine
var Ajax = new AjaxEngine($);
// If form changes or key up in text field
$('.searchForm,.ajaxer>select').on('keyup change',function(e) {
e.preventDefault();
// Serialize the form
var formData = $('.ajaxer').serialize();
// Send the ajax and return results
Ajax.send(formData,function(response) {
$('#searchTable').html(response);
});
});
});
</script>
<!-- Note changes to the form for classes and ids -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="ajaxer">
<input name="search" type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off" />
<div id="here"></div>
<select class="orderType" name="type" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable"></div>

Ajax with PHP same page not working

I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work

Categories