take a value from a select option and use it on php - php

I have this select , i wanna save each value after change , save it and use in other select
This is my code :
<?
$sql = "SELECT * FROM championnat ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="nom_championnat" id="nom_championnat" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option value=" <?php echo $r['idChampionnat']?>" name="nom_championnat" selected >
<?php echo $r['nomChampionnat'] ?></option>
<?php
}
}
}
?>
</select>
</div>
I need the variable $r['idChampionnat'] to save it in each select and use it in this requete , how can it asve and put it in that requete sql ????
<?php
$sql = "SELECT * FROM equipe where idChampionnat=???? ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="equipe1" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option required value=" <?php echo $r['nomEquipe']?>" name="equipe1" selected ><?php echo $r['nomEquipe'] ?>
</option>
<?php
}
}
}
?>
</select>
just to clear it ,

You need to use jQuery to fire an AJAX call when the first box is selected.
Its been a while since I've done this but this should give you some idea. I took some code from here and here as example
Say your html looks like this
<select id="nom_championnat">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="equipe1"></select>
then you need to tell jquery what to do when nom_championnat changes selection
$('#nom_championnat').change(function() {
var data = "";
$.ajax({
type:"POST",
url : "queryfile.php",
data : "value="+$(this).val(),
async: false,
success : function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var string = data.message.split(",");
var array = string.filter(function(e){return e;});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
and then you need a queryfile.php to handle the ajax requests, something like
<?php
print_r($_POST);
$value = $_POST["value"];
$sql = "select where {$value} ..."
$result = execute($sql);
echo $result;
?>

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);
}
});

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

Determining next selection menu by previous selection

I have 3 select drop downs which I want when the first one selected, the second shows up, and when the second is selected, the third one shows up, by using if(isset($_post[first_one])) and for the third one using if(isset($_post[second_one]))
SQL:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM sp_meeting_log ";
$result1 = $conn->query($sql);
PHP/HTML:
<div style="position:absolute; top:300px; left:500px;">
<form method="post">
<p>Choose:</p>
<!--Get all orgs ,forums ,Users data available for admin-->
//select the first
<select style="display:inline-block;" name="org">
<option value="All Orgs">All Orgs</option>
//first drop down info release
<?php
if ($result1->num_rows > 0) {
echo "<table><tr><th>orgID</th><th>orgName</th></tr>";
// output data of each row
while($row = $result1->fetch_assoc()) {
echo "<option>" .$row["orgID"]." /".$row["orgName"]."</option>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</select>
<select style="display:inline-block;" name="forum">
<option value="forum1"><h5>All Forums</h5></option>
<?php
// if the first dropdown post set
if(isset($_POST['org'])){
$result2 = $conn->query($sql);
if ($result2->num_rows > 0) {
echo "<table><tr><th>forumID</th><th>forumName</th></tr>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option>".$row["forumID"]." / ".$row["forumName"]."</option>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
</select>
//select the second
<select style="display:inline-block;" name="user">
<option><h5>All Users</h5></option>
<?php
// if the second drop down is set
if(isset($_POST['forum'])){
$result3 = $conn->query($sql);
if ($result3->num_rows > 0) {
echo "<table><tr><th>userID</th><th>username</th></tr>";
// output data of each row
while($row = $result3->fetch_assoc()) {
echo "<option>".$row["userID"]." / ".$row["username"]. "</option>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
Essentially this is what the idea is. You want page one to just fetch from page two and post the result back to page one into the correct spots:
page1.php
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form>
<label>Org
<select id="org" name="org">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<!-- This is where the forum html will drop into after ajax runs -->
<div id="forum"></div>
<!-- This is where the user html will drop into after ajax runs -->
<div id="user"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
// On change of a select menu
$(this).on('change','select',function(e){
// Assign selection
var thisSelect = $(this);
// Get the id name, this will tell page two
// what it's receiving
var sendType = thisSelect.attr('id');
// Get the actual value of the selection
var sendVal = thisSelect.val();
// Create essentially a POST
var sendData = { field: sendType, value: sendVal };
$.ajax({
// Send to page 2
url : '/page2.php',
// Use post method
type: "POST",
// Use post data from above
data : sendData,
// This is what will run on success
success:function(response){
// Parse the json coming back for placement
var jSon = JSON.parse(response);
// Save the correct html into the correct drop spot
$('#'+jSon.type).html(jSon.html);
},
error: function(response){
console.log(response);
}
});
});
});
</script>
page2.php
if(!empty($_POST)) {
$data = '';
ob_start();
if(isset($_POST['field'])) {
if($_POST['field'] == 'org') {
$type = 'forum';
?>
<label>Forum
<select id="forum" name="forum">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<?php
}
elseif($_POST['field'] == 'forum') {
$type = 'user';
?>
<label>user
<select id="user" name="user">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<?php }
$data = ob_get_contents();
ob_end_clean();
die(json_encode(array('type'=>$type,'html'=>$data)));
}
die(json_encode(array('type'=>'error','html'=>false)));
}

How I change query onclick combobox event in php?

I am new with php.I want to change query when some event occur on ComboBox. So that according to that query I retrieve data from database in php.The code is given below:-
<form method="POST" action="">
<select id="choose-color">
<option value="all">All</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</form>
<?php
$conn = mysqli_connect("localhost","root","123");
mysqli_select_db($conn,"DwtCW");
$q = "Select * from Clothes";
$result = mysqli_query($conn, $q);
if (!$result) {
echo 'Some error';
}
while($row = mysqli_fetch_assoc($result)){
if($row{'Image_url'} != ''){
echo '<div>'
. '<img src='.$row{'Image_url'}.'/>'
.'</div>'
}
?>
When I select blue option of ComboBox my $q(query given in above code) is change to
$q = "Select * from Clothes where colour = 'blue'";
So there should appear only images of clothes having blue colour onpage.
How I reach it?
you need to send ajax request to PHP page. onChange event will trigger ajax request and will change query.
<form method="POST" action="">
<select id="choose-color">
<option value="all">All</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$('#choose-color').on('change', function(){
var color = $(this).val();
if(color){
$.ajax({
type: "GET",
url: "index.php", //or your php page
data: { color: color }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
</script>
<?php
$conn = mysqli_connect("localhost","root","123");
mysqli_select_db($conn,"DwtCW");
$whr = ' ';
// check if color is posted on change event
if ( isset($_GET['color'] ) ) {
$whr .= " where colour = '".$color."' ";
}
$q = "Select * from Clothes $whr";
$result = mysqli_query($conn, $q);
if (!$result) {
echo 'Some error';
}
while($row = mysqli_fetch_assoc($result)){
if($row{'Image_url'} == ''){
echo '<div>'
. '<img src='.$row{'Image_url'}.'/>'
.'</div>'
}
?>

Using Ajax, jQuery and PHP in two dropdown lists

I am trying to populate second dropdown list based on first dropdown list selection using Ajax, jQuery, PHP and MySQL. The problem is the options in second dropdown list just appears in one line (all options in one line)!
I was hoping the while loop inside the results.php could handle this but it seems not. How can I fix this issue?
Here is my code:
<html>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM Cars';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a Car
<select id="selectCar">
<option value="select">Please Select From The List</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
}
?>
</select>
</p>
<select>
<option value="select">Please Select From The List</option>
<option id="result"></option>
</select>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCar').change(function()
{
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
In the PHP result I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$resultStr = '';
$query = 'SELECT * FROM models WHERE carID='.$_GET['id'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$resultStr.= '<option value="'.$row['id'].'">'.$row['model'].'</option>';
}
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
You should edit your script into this..
<select id="result">
<option value="select">Please Select From The List</option>
</select>
You are setting $('#result').html(data); in the main file.
result should be the id of the HTML select element, you used it as id for the an option element.
(You are appending the values into the option element, which doesn't create new HTML elements, but they should be inserted into the select element.)

Categories