I've a html form where the countries in the drop down are coming from a database. If user selects any country, then the city drop diwn will appear based on selected country.
If user wrongly input any field of the form (there are other field in this form) then country drop down will will remember which country the user initially selected, but clears the city, resetting it to --Select City--. I'm trying to selected the city name but I can't. Any idea ?
Ajax Code here:
<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()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
ajax_city.php here
<?php
require_once("toplevel/content/database/databd.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select Name from cities WHERE CountryCode ='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];
if($_POST['city'] == $data)
{
$sel = 'selected = "selected"';
}
else
{
$sel = " ";
}
echo '<option value="'.$data.'" ' .$sel . ' >'.$data.'</option>';
}
}
?>
Html form here:
<tr>
<td>PAYS <span style="color: #FF0000;">*</span></td>
<td>
<select name="country" class="country">
<option value="">Select</option>
<?php
$sql=mysql_query("select * from country");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];
$data = mb_convert_encoding($data, 'UTF-8');
if($id == $_POST['country'])
{
$sel = 'selected="selected"';
}
else
{
$sel = "";
}
echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select class="city" name="city">
<option selected="selected" value="">--Select City--</option>
</select>
</td>
</tr>
Not quite sure but issue is in datastring try changing this:
$(".country").change(function(){
var id=$(this).val();
var dataString = {'id': id};
$.ajax({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html){
$(".city").html(html);
}
});
});
You will need to rebuild your HTML on reload, but now with your City list (this is untested, but based on your code from the Country dropdown):
<tr>
<td>City</td>
<td>
<select class="city" name="city">
<option selected="selected" value="">--Select City--</option>
<?php
if (isset($_POST['city']) {
$sql=mysql_query("select * from city");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];
$data = mb_convert_encoding($data, 'UTF-8');
if($id == $_POST['city']) { $sel = 'selected="selected"'; }
else { $sel = ""; }
echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
}
}
?>
</select>
</td>
</tr>
WARNING: This is just same sample code. This should never ever go into production, because it has the potential for being extremely unsafe! As #PolishPrince has pointed out above, you should at least use PDO or MySQLi.
Related
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);
}
});
So i want to make my select dropdown box flexible, however i tried using AJAX which i found online, but the AJAX request is a standalone data, it does not return back the data.
Is there any convenient way to get the data and able to submit to another PHP file ?
Here is my Code
index.php
<td>
<select id="ownerID" name="OwnerID" class="id" required>
<?php
$Employee_ID='';
$sql1="SELECT Employee_ID FROM user1 WHERE Position1='QE' OR Position1='OTHER'";
$result1=odbc_exec($conn,$sql1);?>
<option value="">Choose</option>
<?php while($row1=odbc_fetch_array($result1)){
$Employee_ID=$row1['Employee_ID'];
?>
<option value ="<?php echo $Employee_ID;?>"><?php echo $Employee_ID;?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td id="response" style="margin-left:50px;">
</td>
AJAX
<script type="text/javascript">
$(document).ready(function(){
$("select.id").change(function(){
$("#response option").remove();
var selectedOwner = $(".id option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { id : selectedOwner}
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
post-requst.php
if(isset($_POST["id"])){
$id = $_POST["id"];
$Form_Tracking_ID=null;
$sql="SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID = ' '
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID = ' '";
$result=odbc_exec($conn,$sql);
if($id !== 'Choose'){
echo "<label>Tool ID:</label>";
echo "<br><select id='toolid' name='ownerid' required>"; ?>
<option value="">Choose</option>
<?php while($row=odbc_fetch_array($result)){
$search=$row['Form_Tracking_ID']; ?>
<option value="<?php echo $search ?>"><?php echo $search ?></option>
<?php }
echo "</select>";
}
}
You can use a function for get data from database, getting value of 1º select and put them on 2º select
//Get value from 1 select
$("#firstSelect").change(function () {
let firstSelectValue = $("#firstSelect").val();
$("#secondSelect").text("");
//Calling a function to get value from database
getDataForSecondSelect(firstSelectId);
})
function getDataForSecondSelect(firstSelectValue) {
$.ajax({
url: `getDataForSecondSelect.php?value=${firstSelectValue}`,
method: "GET",
dataType: "JSON",
success: function (message) {
if (message.length != 0) {
$('#secondSelect').prop('disabled', false);
for (let i = 0; i <= message.length; i++) {
$("#secondSelect").prepend(`<option value=${message[i]["id"]}>${message[i]["name"]}</option>`);
}
} else {
$("#subcategoriaProduto").text("");
$("#subcategoriaProduto").prepend("<option>There's no data</option>");
$('#subcategoriaProduto').prop('disabled', true);
}
}
});
}
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);
?>
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?.
I got 3 drop down boxes dependent on each other when selected. For e.g. if I select a type from drop down 1, then drop down 2 populates only the options relevant to what i select from the first drop down box. The 3rd drop down is dependable on the 2nd drop down option.
The problem i am facing is that the options on the drop down boxes are not refreshing when i want to choose something different.
Can anyone help me?
This is my form:
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country</label>
<select id="country" name="country" class="country" required>
<option value="" selected="selected">-- Select --</option>
</select>
<label>Destination</label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
</select>
This is the js at the bottom of the form:
<script>
$('#tourtype').change(function () {
var id = $(this).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {
id: id,
get_countries: 1
},
success: function (html) {
$("#country").empty();
$("#country").append(html);
},
error: function () {
alert("ajax failed");
}
});
});
$('#country').change(function () {
var id = $(this).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {
id: id,
get_destination: 1
},
success: function (html) {
$("#destination").empty();
$("#destination").append(html);
},
error: function () {
alert("ajax failed");
}
});
});
</script>
Finally this is the ajax.php
<?php
include('../config.php');
if ($_REQUEST['get_countries']) {
$sql = mysql_query("SELECT * FROM `countries` WHERE `tour_type_id`=" . $_REQUEST['id']);
$countries = "";
while ($row = mysql_fetch_array($sql)) {
$cid = $row['countries_id'];
$name = $row['countries_name'];
$countries .= "<option value='" . $cid . "'>" . $name . "</option>";
}
echo $countries;
} elseif ($_REQUEST['get_destination']) {
$destination = "";
$sql = mysql_query("SELECT * FROM `destination` where `country_id` =" . $_REQUEST['id']);
while ($row = mysql_fetch_array($sql)) {
$destination_id = $row['destination_id'];
$name = $row['destination_name'];
$destination .= "<option value='" . $destination_id . "'>" . $name . "</option>";
}
echo $destination;
}
?>
I have fixed the problem. Just had to add more data to the 3 separate tables where my query is fetching the data from