get data from combo box using jquery and ajax - php

i'm just learning about jquery and ajax, trying to create combo box and get the data based on the combo box value
here is my code on index.php
<form action="cari.php" method="post">
<select name="kamar">
<option value="regular single">Regular Single Rp 99.000</option>
<option value="regular double">Regular Double Rp 120.000</option>
<option value="family single">Family Single Rp 127.500</option>
<option value="family double">Family Double Rp 150.000</option>
<option value="vip single">V.I.P Single Rp 170.000</option>
<option value="vip double">V.I.P Double Rp 200.000</option>
</select>
<input type="submit" value="submit" name="submit">
</form>
<br>
<div id="tampil"></div>
<script>
$(document).ready(function(){
loadData();
$('form').on('submit', function(e)
{
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success:function(){
loadData();
},
});
})
})
function loadData(){
$.get("tampil3.php", function(data){
$("#tampil").html(data)
})
}
</script>
here for cari.php
<?php
include "koneksi.php";
$jenis = $_POST['kamar'];
$sql= "select * from kamar where jkamar = '$jenis' ";
$result = mysqli_query($conn, $sql);
?>
<table cellpadding=2 cellspacing=2>
<?php
if(mysqli_num_rows($result) > 0)
{
while ($data = mysqli_fetch_array($result))
{
?>
<tr><?php echo $data['nokamar']; ?></tr>
<?php
}
}
else
{
echo "no more data!";
}
?>
</table>
tampil3.php, for getting all records from database
<?php
include "koneksi.php";
$sql= "select * from kamar";
$result = mysqli_query($conn, $sql);
?>
<table border=1 cellpadding=2 cellspacing=2>
<?php
if(mysqli_num_rows($result) > 0)
{
while ($data = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $data['nokamar']; ?></td>
</tr>
<?php
}
}
else
{
echo "no more data!";
}
?>
</table>
i already tried this code and its not working, any help?
any suggestion will be appreciated
thanks!

Related

AJAX POST Not Returning php mysql ajax

I'm trying to get data from the database using ajax to insert it in other element but the post data not passing to get-data.php
so what the reason can be and the solution
addBuilding.php
<?php
require_once("./dbConfig.php");
$selectIL = "SELECT * FROM iller ";
$selectIL = $db->prepare($selectIL);
$selectIL->execute();
$res = $selectIL->get_result();
?>
<form action="" method="post">
<select name="pp" id="cites">
<option value="">-select state-</option>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['il_adi'] ?></option>
<?php
}
?>
</select>
<select name="district" id="district">
<option value="">-select district-</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="getdata.js"></script>
getdata.js
$(document).ready(function() {
$("#cites").change(function() {
if ( $("#cites").val()!="") {
$("#district").prop("disabled",false);
}else {
$("#district").prop("disabled",true);
}
var city = $("#cites").val();
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
success: function(result) {
$("#district").append(result);
}
});
});
});
get-data.php
I can see the form data in network inspection put no data passing to get-data.php
<?php
require_once("./dbConfig.php");
if (isset($_POST['pp'])) {
$cites = $_POST['cites'];
$selectIlce = "SELECT * FROM ilceler where il_id=? ";
$selectIlce = $db->prepare($selectIlce);
$selectIlce->bind_param("i", $cites);
$selectIlce->execute();
$res = $selectIlce->get_result();
?>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['ilce_adi'] ?></option>
<?php
}
}
?>
You need to echo the results in get-data.php
<?php
while ($row = $res->fetch_assoc()) {
?>
echo "<option value='". $row["id"]."'>".$row['ilce_adi']."</option>";
<?php
}
}
?>
1- Get data by serialize from form:
$("form").serialize()
2- Add dataType: "json" to ajax option:
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
dataType: "json",
success: function(result) {
$("#district").append(result);
}
});

Binding dropdown list to mysql database in php

Okay so this is my table 'timings'
Table 'timings'
I'm showing this data in a table, and I want the availability to be updated whenever the availability is selected to a different value by the user. This is the code for the table:
<!-- Table for timings-->
<table id="tableCreneaux">
<tr>
<th> Créneau </th>
<th> Disponibilité</th>
</tr>
<?php
$sql_check = 'SELECT * FROM timings ORDER BY timingOrder';
$res_check = mysqli_query($conn, $sql_check);
if(mysqli_num_rows($res_check) > 0){
while($row =mysqli_fetch_assoc($res_check)){
$creneau = $row["timing"];
$statutCreneau = $row["available"];
echo '<tr>';
echo '<td>'.$creneau.'</td><td> <select id="statut'.$creneau.'">';
if($statutCreneau == 1)
{
echo '<option value="available"> Disponible </option> <option value="unavailable"> Non disponible </option> ';
}
else
{
echo '<option value="unavailable"> Non disponible </option><option value="available"> Disponible </option> ';
}
echo '</select> </td> </tr>';
}
}
?>
</table>
How do i bind the database's 'available' value to the value of the dropdown list?
1-you should use javascript code for update database on change
2-your select should be out of while{}
HTML:
<select id="select" onchange="update_database()">
while(condition){
<option...> </option>
}
</select>
AJAX SCRIPT:
<script>
function updatae_database(val)
{
$.ajax({
url: 'send.php', // The PHP file that you want to send your user input to
type: 'POST',
data: {data: $('#select').val()}, // The data to be sent
dataType: 'text',
success: function(data)
{
alert('update successful');
}
});
}
</script>
send.php :
<?php
include('database.php');
$name = $age = $id ="";
if(isset($_GET['data']))
{$data=$_GET['data'];}
$query = "update TABLE set COLUMN='$data'";
$sql = mysqli_query($con,$query);
?>

Dependent Dropdown list

I am newbie to JQuery Ajax. May i know how to create a PHP to read the subcategory list depends on the selected maincategory? So far i had create a jQuery AJAX in my asset_add.php
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#main_category').on('change',function(){
var categoryNAME = $(this).val();
if(categoryNAME){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'ac_maincategory='+categoryNAME,
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
});
});
</script>
and for HTML,
<tr>
<td valign=top><strong>MAIN CATEGORY</td>
<td><select name="main_category" id="main_category" onchange="this.form.submit()" required>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
?>
<option value=""></option>
<?php
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_maincategory = $rs["ac_maincategory"];
$ac_id = $rs["ac_id"];
?>
<option value="<?=$ac_id?>"><?=$ac_maincategory?></option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign=top><strong>SUB CATEGORY</td>
<td><select id= "sub_category" name="sub_category" autocomplete="off"/ required>
<option value=""></option>
</select>
</tr>
while in my ajaxData.php
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
However, when i choose a maincategory in asset_add.php, nothing shown in subcategory. Can anyone tell me which part i do wrong? Thanks for help
Seems you are replacing whole div with $('#sub_category').html(html); so there is only options printed on the view
You can solve it by replacing the line
$('#sub_category').html(html);
to
$('#sub_category').append(html);
Or Just replace this code in ajaxData.php , S
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(empty($_POST["ac_maincategory"])){
die("category is empty");
}
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = " . $_POST['ac_maincategory'];
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo '<select id= "sub_category" name="sub_category" autocomplete="off"/ required>';
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
echo "</select>";
}
this is simple question and should be fixed ASAP. but idk why still not solved yet.
so, please try this
html
remove onchange attribute (remove native js event trigger style with jquery style)
optional:
fix several unclosed tag html
remove unrecomended PHP writing style
into this
<tr>
<td valign="top"><strong>MAIN CATEGORY</strong></td>
<td>
<select name="main_category" id="main_category" required>
<option value=""></option>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
echo '<option value="'. $rs["ac_id"] .'">'.$rs["ac_maincategory"].'</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign="top"><strong>SUB CATEGORY</strong></td>
<td>
<select id= "sub_category" name="sub_category" autocomplete="off" required>
<option value="">Select main category first</option>
</select>
</td>
</tr>
jquery
change on('change') with change() // possible dont know when to use on or not
change wrong comparasion on categoryNAME
optional:
change serialize data style using data {} //better for newbie to study
into this
<script>
$(function(){
$('#main-category').change(, function(){
var categoryNAME = $(this).val();
if(categoryNAME != ''){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{ac_maincategory: categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
})
});
</script>
PHP
reposition default sub-category value out of $count comparasion
into this
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
echo '<option value="">Select Subcategory</option>';
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
<?php
//.....
//you sql......$result
//.....
if($_POST['ac_maincategory']) {
//this is test
if($_POST['ac_maincategory']=="aaa"){
$result=array("k1"=>"v1","k2"=>"v2");
}else{
$result=array("kk1"=>"v11","kk2"=>"v22");
}
$str = '<option value="">Select Subcategory</option>';
foreach ($result as $k => $v) {
$str .= '<option value="' . $k . '">' . $v . '</option>';
}
echo $str;exit;
}
?>
<html>
<head></head>
<body>
<div>
<select id="main_category">
<option value=""></option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
</select>
</div>
<div>
<select id="sub_category">
<option value=""></option>
</select>
</div>
</body>
</html>
<script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
<script>
$("#main_category").change(function () {
var categoryNAME=$(this).val();
$.ajax({
type:'POST',
url:'',
data:{"ac_maincategory":categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
})
</script>
test image
https://i.stack.imgur.com/oJLKo.png
https://i.stack.imgur.com/oIw03.png
https://i.stack.imgur.com/vQQrz.png

Dependent dropdown list working in php and not working in codeigniter

In the below code when i worked in php the dropdown are working well when exam name is selected corresponding course_code came and when i selected corresponding subject_code came.But Now i created controller and call the view in codeigniter when i select exam_name it is not populating the values and when i click upload it shows the course_code values and not populating subject_coide and when i click upload it populates subject_code.So anyone pls help me.
Upload1_site (controller)
<?php
class Upload1_site extends ci_controller
{
function index()
{
$this->load->view('new_view');
}
function upload()
{
$this->load->view('new1_view');
}
}//end of class ?>
new_view (View 1)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".hai").change(function()
{
var id=$(this).val();
// Please find the course_code, course_code was not found
var dataString = 'course_code='+ id;
$.ajax
({
type: "POST",
url: "upload1_site/upload",
data: dataString,
cache: false,
success: function(html)
{
$(".hai2").html(html);
}
});
});
$(".hai2").change(function()
{
var id2=$("#hai2").val();
alert(id2);
var dataString = 'subject_code='+ id2;
$.ajax
({
type: "POST",
url: "upload1_site/upload",
data: dataString,
cache: false,
success: function(html)
{
$(".hai3").html(html);
}
});
});
});
</script>
</head>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
File to import:
<input size='30' type='file' name='filename'>
<br>
Select Exam name:
<select name="hai" class="hai" id="hai">
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("slseatapp") or die(mysql_error());
$query="select distinct exam_name from examcourse";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['exam_name']."'>".$nt['exam_name']."</option>";
}
?>
</select>
<br>
<span class="hai2">
Course code:
<select name="hai2" id="hai2">
<?php if($_REQUEST['hai']){?>
<option>Select</option>
<?php
$query="SELECT distinct course_code FROM examcourse where exam_name = '".$_REQUEST['hai']."' ";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['course_code']."'>".$nt['course_code']."</option>";
}
?>
<?php }else{?>
<option>Select</option>
<?php }?>
</select>
</span>
<br>
<span class="hai3">
Subject code:
<select name="hai3" id="hai3">
<?php if($_REQUEST['hai2']){?>
<option>Select</option>
<?php
$query="SELECT distinct subject_code FROM coursesubject where course_code = '".$_REQUEST['hai2']."'";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['subject_code']."'>".$nt['subject_code']."</option>";
}
?>
<?php }else{?>
<option>Select</option>
<?php }?>
</select>
</span>
<br>
<input type="submit" name="submit" value="Upload"></form>
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("slseatapp") or die(mysql_error());
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
//Import uploaded file to Database
$row = 1;
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$var = $_POST['hai'];
$var2 = $_POST['hai2'];
$var3 = $_POST['hai3'];
//$res=mysql_fetch_array(mysql_query("SELECT subject_code FROM coursesubject where course_code = '".$var1."'"));
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//Update Database Values
$import="insert into student_table (id,register_number,name,course_code,subject_code,exam_name) VALUES('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[1])."','".mysql_real_escape_string($data[2])."','$var2','".$var3."','$var')";
//$import="replace into student_table (id,register_number,name,course_code,subject_code,exam_name) VALUES('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[1])."','".mysql_real_escape_string($data[2])."','$var','$var1','$var2')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
echo"<script>alert('Uploaded Successfully');</script>";
}else{
echo"<script>alert('Failed');</script>";
}
}
?>
new2_view (view 2)
<script language="javascript">
function changeSelection(value){
var length = document.getElementById("hai3").options.length;
if(value == 0){
for(var i = 1;i<length;i++)
document.getElementById("hai3").options[i].selected = "selected";
document.getElementById("hai3").options[0].selected = "";
}
}
</script>
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("slseatapp") or die(mysql_error());
if($_POST['course_code']){
#$exam_name=$_POST['course_code'];
?>
Course code: <select name="hai2" id="hai2">
<option >Select</option>
<?php
$query="SELECT distinct course_code FROM examcourse where exam_name = '$exam_name' ";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['course_code']."'>".$nt['course_code']."</option>";
}
?>
</select>
<?php }
if($_POST['subject_code']){
#$subject_code=$_POST['subject_code'];
?>
Subject code:
<select name="hai3" multiple onChange="changeSelection(this.value)" id="hai3">
<option value="0">Select</option>
<?php
$query="SELECT subject_code FROM coursesubject where course_code = '".$subject_code."'";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['subject_code']."'>".$nt['subject_code']."</option>";
}
?>
</select>
<?php }?>
try this one
put this one
var base_url="<?=base_url()?>"
somewhere inside the script tag may be before
$(document).ready(function(){
line
and change the line
url: "upload1_site/upload",
with
url: base_url+"upload1_site/upload",
please let me know if it works or not.

Chained ajax Select Boxes

I have some problems with my html/php/ajax code about dependent (or chained) select. I want to show in my menu the list of faculties after I have decided the university.
I'll show you my (italian) code. I hope you'll help me. Thanks.
javascript ajax code:
<script type="text/javascript">
$(document).ready(function()
{
$(".universita").change(function()
{
var dataString = 'id='+ $(this).val();
$.ajax
({
type: "POST",
url: "ajax_facolta.php",
data: dataString,
cache: false,
success: function(html)
{
$(".facolta").html(html);
}
});
});
});
html code about two select boxes:
<td align="right">Università: </td>
<td>
<select class="input" name="universita">
<option selected="selected">--Seleziona Università--</option>
<?php
require('config.php');
$query = mysqli_query($con, "SELECT * FROM UNIVERSITA order by id ASC");
$num_righe = mysqli_num_rows($query);
for($x=0; $x<$num_righe; $x++)
{
$rs = mysqli_fetch_row($query);
$id = $rs[0];
$nome = $rs[1];
?>
<option value="<?php echo $id;?>"> <?php echo $nome; ?></option>
<?php
}
?>
</select></td>
</tr>
<tr>
<td align="right">Facoltà: </td>
<td><select class="input" name="facolta">
<option selected="selected">--Seleziona Facoltà--</option>
</select></td>
</tr>
the file ajax_facolta.php:
<?php
require('config.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql = mysqli_query($con, "SELECT * FROM FACOLTA WHERE id_univ='$id' ");
echo '<option selected="selected">--Selziona Facoltà--</option>';
while($row=mysqli_fetch_array($sql))
{
$id=$row['id'];
$nome=$row['nome'];
echo '<option value="'.$id.'">'.$nome.'</option>';
}
}
?>
and the simple configure.php:
<?php
$con = mysqli_connect("127.6.143.130","xxxxx","xxxxx", "jeme");
if (!$con)
{
die('Errore nella connessione: ' . mysqli_connect_error());
}
?>
The database is very simple.
UNIVERSITA has (id, nome)
FACOLTA has (id, nome, id_univ).
I do not find any errors but it does not work. Thanks for the help.
In HTML you have :
<select class="input" name="universita">
and you are using
$(".universita").change(function()
$(".universita") will try to search HTML control having class name "universita"
So change few things in code. I hope it will work
1). <select class="input" name="universita" id="universita">
2). $("#universita").change(function()
3). <td><select class="input" name="facolta" id="facolta">
4). $("#facolta").html(html);
let me know is this helpfully?.

Categories