Update select options based on other selected option from database - javascript

I have a form which selects regions, provinces, and cities. The select options for provinces depends on the selected region and the options for cities depends on the selected province. All the options are from the database
I have already made the region show up with this code.
<select class="form-control" id="region" name="region">
<?php
if( isset($Region) && count($Region)>0 ){
foreach($Region as $Region){
echo '
<option>'.$Region['region'].'</option>
';
}
}else{
echo '
<option>NO RECORDS FOUND</option>
';
}
?>
</select>
Could you please help me on my next step which is to display the options for provinces?
<select class="form-control" id="province" name="province">
</select>
I believe after achieving this step I would be able to do the same for displaying cities. Thank you!
Database name: patrol
table name: geography
>id
>region
>province
>city
I've tried the same as this one by putting this script
<script>
$(function() {
$(document).ready(function () {
$('#region').change(function() {
var select = $('#province').empty();
$.get('script.php', {region: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
});
</script>
and having this script.php
<?php
if (isset($_GET['region'])) {
$sql = new mysqli('localhost','root','','patrol');
$region = mysqli_real_escape_string($sql,$_GET['region']);
$query = "SELECT * FROM geography WHERE region = $region";
$ret = $sql->query($query);
$result = array();
while ($row = $ret->fetch_assoc()) {
$result[] = array(
'value' => $row['id'],
'name' => $row['province']
);
}
echo json_encode($result);
}
?>

<option>'.$Region['region'].'</option>
You did not set any value in region select option.
It should be like below:
<option value="'.$Region['region'].'">'.$Region['region'].'</option>
also use console.log(result) to see you are getting expected data back or not.

Thank you for answering guys. However, I have found an answer and it did the fix. I'll post the script for others who have the same question as mine
<script type="text/javascript">
$(document).ready(function()
{
$("#region").change(function()
{
var region= document.getElementById("region").value;
var dataString = 'region='+ region;
$.ajax
({
type: "POST",
url: "get_province.php",
data: dataString,
cache: false,
success: function(html)
{
$("#province").html(html);
}
});
});
$("#region").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
$("#province").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
});
</script>

Related

Cannot view option value html(data)

i want to show my select option value with Ajax jQuery
here is
JS:
$('#jenis_jab').change(function(){
var jab = $(this).find('option:selected').text();
$.ajax({
url : 'proses/ajax_process.php?aksi=jenis_jab',
type : 'POST',
data : 'jab=' + jab,
dataType: 'text',
success:function(data) {
$('#uk').html(data);
}
});
});
PHP:
if(isset( $_GET['aksi']) && $_GET['aksi']=='jenis_jab') {
$jab = $_POST['jab'];
$sql = $db->query("SELECT * FROM tbl_unit_kerja WHERE jabatan='$jab'");
while($data = $sql->fetch_array()) {
echo "<option value=$data[id]>$data[unit_kerja]</option>";
}
}
HTML:
<select id="uk"></select>
I use materializecss
this is work for html div, but for option value is not working
what's wrong?
thanks
sorry it's done with
$('#uk').change(function(){
var uk = $(this).find('option:selected').val();
$.ajax({
url : 'proses/ajax_process.php?aksi=unit_kerja',
type : 'POST',
data : 'uk=' + uk,
dataType: 'text',
success:function(data) {
$('#suk').html(data);
$('#suk').material_select();
}
});
});

Populate select box when document load

im trying to populate a select box from values in my database after the document load, or ready. I'm new to ajax and jquery, Can someone help find what's wrong to my code?
<select class="form-control sec" id="sec" name="sec">
<option value="sec">Section</option>
</select>
here's my ajax code.
function loadselectbox(){
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"load": 1,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var select = $("#sec"), options = '';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'>";
}
select.append(options);
}
});
}
here's my getrecords.php
if (isset($_POST['load'])) {
$fac_code = $_POST['fac_code'];
$select = mysqli_query($con,"SELECT * FROM tfile WHERE faculty_code = '$fac_code'");
while ($row = mysql_fetch_array($select)) {
$result[] = array(
'section' => $row['section'],
'subj_descr' => $row['subj_descr']
);
}
echo json_encode($result);
}
i call the function in document.ready
$(document).ready(function() {
loaddata();
loadselectbox();
});
Try this:
$(document).ready(function(){
var fac_code = $("#faculty_code").val();
$.ajax({
url: 'getrecords.php',
type: 'POST',
data: {
"load": 1,
"fac_code": fac_code
},
success: function(response){ // response contains json object in it
var data = JSON.parse(response);
var options = '<option value=""></option>';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'> +data[i].subj_descr+ </option>";
}
$("#sec").html(options); // It will put the dynamic <option> set into the dropdown
}
});
});

Pass values from JQUERY to PHP then output to INPUT in FORM

i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});

Adding table rows based on JSON

I'm new with JSON. I have a select box and JavaScript change() trigger on it. I execute MySQL query with Ajax based on selected value. Query results will be printed as a new row in HTML table.
But the new row isn't appending. What am I doing wrong?
HTML
<select id="orderAddProduct">
<option value=""></option>
<option value="0001">Product 1</option>
<option value="0002">Product 2</option>
</select>
<table id="orderTable">
<tr><th>ID</th><th>Name</th></tr>
</table>
JavaScript
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "POST",
url: "orderAddProduct.php",
data: {option: selectedValue},
datatype: "json",
success: function (data) {
alert("OK");
orderAddRow(data);
},
error: function () {
alert("ERROR");
}
});
});
function orderAddRow($item) {
$.each($item,function(index,value) {
var row = '<tr><td>'+value.id+'</td>'
+'<td>'+value.name+'</td></tr>';
$('#orderTable').append(row);
)};
}
PHP
try {
$pdo = new PDO(DB_TYPE . ':host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
$productId = $_REQUEST['option'];
$sql = $pdo->prepare("SELECT * FROM products_view WHERE id = ?");
$sql->execute(array($productId));
$row = $sql->fetch(PDO::FETCH_ASSOC);
$json_array = array("ID" => $row['id'], "name" => $row['name']);
echo json_encode($json_array);
Variable names?
function orderAddRow($item) {
^^^^^^----
var row = '<tr><td>'+value.id+'</td>'
^^^^^----
You define a $item parameter, but never use it in the function. Instead there's this mysterious/undefined value.
Ok, the master problem is that I didn't have JSON.parse() function in my code. Below is my finally working code.
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "GET",
url: "orderAddProduct.php",
data: {option : selectedValue},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
return false;
});
function orderAddRow($data) {
$.each($data,function(index,value) {
var row = '<tr><td>' + value.ID + '</td>'
+ '<td>' + value.name + '</td></tr>';
$('#orderTable').append(row);
});
}
success: function (data) {
alert("OK");
orderAddRow(data);
},
You are missing out the returned value.

ajax and javascript drilldown script addition

I have a make/model/engine search form, the user selects the make which then populates the model, the user selects the model and it populates the engine. The problem I have encountered is that several of the manufacturers (make) use the exact same model. The script I have chooses the engine based on the model only. I would like to modify the script so it chooses the engine based on the make AND model, this would resolve my problem. I am somewhat familiar with javascript but I am no expert, I see the ajax requests in the aircraftMakeModel.php file but do not know how to add the make to the query. I have included the three files used below. Any help is appreciated in advance.
Thanks
Tom
aircraftMakeModel.php
<script type="text/javascript">
$(document).ready(function()
{
$('#aircraftMake').change(function()
{
var make=$(this).val();
var dataString = 'make='+ make;
$.ajax
({
type: "POST",
url: "include/getAirFrame.php",
data: dataString,
cache: false,
success: function(html)
{
$('#aircraftModel').html(html);
}
});
});
});
$(document).ready(function()
{
$('#aircraftModel').change(function()
{
var model=$(this).val();
var dataString = 'model='+ model;
$.ajax
({
type: "POST",
url: "include/getEngine.php",
data: dataString,
cache: false,
success: function(html)
{
$('#engineModel').html(html);
}
});
});
});
</script>
getAirFrame.php
<?php
include "../connection.php";
$q = $_POST['make'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`aircraftModel`) FROM `aircraftData` WHERE `aircraftMake` = '$q' ORDER BY aircraftModel ; ");
echo '<option value="0">Aircraft Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
getEngine.php
<?php
include "../connection.php";
$q = $_POST['model'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`engineModel`) FROM `aircraftData` WHERE `aircraftModel` = '$q' ORDER BY engineModel");
echo '<option value="0">Engine Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
If you want to send the make and model on the ajax call to get the engine something like this should work. Make the call to get the model as you do, then also add the make to the ajax request data to get the engine.
Note: not sure if this is a typo $('#marke')
$(document).ready(function(){
$('#marke').change(function() {
//make id
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "include/getph.php",
data: dataString,
cache: false,
success: function(html) {
$('#model').html(html);
}
});
});
});
$(document).ready(function() {
$('#model').change(function(){
//make id
var id = $('#marke option:selected').val();
//model id
var id1=$(this).val();
var dataString = 'id1='+ id1 + '&id=' + id;
$.ajax({
type: "POST",
url: "include/getph2.php",
data: dataString,
cache: false,
success: function(html) {
$('#engine').html(html);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources