I have a code, where when i select a value through Drop-down, the name I am selecting should pass through a PHP variable $ch so a second drop-down which runs a mysql query.
Here is my code for first dropdown:
<select name="cha_name" id="cha_name" onChange="fillcha(this.value);">
<option value="0">--SELECT--</option>
<?php
$res = mysqli_query($con, "select customer_code, customer from master_customer where is_cha = 1 order by customer") or die(mysqli_error($con));
while($row = mysqli_fetch_array($res)){
echo "<option value=\"".$row[1]."$$".$row[0]."\" ".(($row[1]==$wo_order[1])?"selected='selected'":"").">".$row[1]."</option>";
}
?>
</select>
When i select this, the value should be capture in a PHP variable $ch without reloading the page show the PHP variable can be used further in a mysql query. Kindly help as I am still in learning phase for JQuery and Ajax.
the mysql query is as follows:
SELECT container_no FROM `cex_work_order_det` WHERE `cha_name`='$cha'
for that you have to use jquery and ajax
jquery code
<script>
$("document").ready(function()
{
$("select[name='cha_name']").change(function() // function sorting Domain according to server name
{
var customer_code=$("select[name='cha_name']").val();
$.get('ajax_actions.php?act=your-act-name&customer_code='+customer_code,function(data)
{
alert(data);
});
});
});
</script>
ajax_actions.php
<?php
error_reporting(0);
foreach ($_GET as $name => $value) { $$name = $value; }
foreach ($_POST as $name => $value) { $$name = $value; }
// warning Dont chnage anything in This ajax action file
// -------------------------------------------------------------------------------
if($act=="your-act-name") // do your actions
{
// fire here your query and echo you result here
}
Related
I'm programming a simple form with a dynamic dependent selection. There are two files. One is a php file with html, javascript and php inside, the second is a php file to get data for the second selection and send them back in json format. In the first (and main) file I have the form with two select fields. First field is for province, second is for towns. Data are in a MySQL db, two tables, table_provinces for provinces (103 rows) and table_towns for towns (8000 rows). Normally connect to the db as usual and also link to jquery using a javascript link. First I get provinces options for the first select field, using php to get the values from table_provinces of the db. Then with the javascript " on('change',function(){ here I use ajax...}) " I pass the selected value using ajax to a php file that might extract towns from table_towns and give back (in json format) values to populate the second select field. Javascript gets correctly the selected value from the first selection field (I used an alert to know it), but nothing more happens. So this is the code.
Link to jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
HTML first select field:
<form method="post" action="usemychoice.php">
<select id="province" name="province" color="white">
<option value="" selected>Select a province</option>
This is how I populate the first select field:
<?php
$sql = "SELECT * FROM table_provinces";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['prov']."'>".$row['extended_province']."</option>";
}
} else {
echo "Error: ..........";
}
?>
And after closing that field with a /select I have this code to get values for populating with town names the second select field:
<script type="text/javascript">
$(document).ready(function(){
$('#province').on('change',function(){
var provinceID = $(this).val();
if(provinceID){
window.alert("ok you've chosen the province "+provinceID);
$.ajax({
type:'POST',
url:'get_towns.php',
data: 'prov='+provinceID,
success:function(html){
$('#town').html(html);
}
});
}else{
$('#town').html('<option value="">Please select the province first</option>');
}
});
});
</script>
This is the get_town.php code:
<?php
//*****after a require to the connection db routine"
if(!empty($_POST["prov"])) {
$sql = "SELECT * FROM table_towns WHERE prov LIKE '%" .$_POST['prov']."%'";
$result = mysqli_query($conn, $sql);
$json = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
} else {
echo "Error: .................";
}
echo json_encode($json);
}
?>
Finally I have the html code :
<select id="town" name="town" color="white">
<option value="" selected>Select province first</option>
At the end of the day, the code has something wrong because I don't get any data back from get_town.php to populate the second select field, and since I didn't see a window.alert that I've put there to check ongoing execution (you don't see it in the code posted here), it seems that is not executed. Any help?
url:'get_towns.php',
Isn't it get_town.php without plural ?
Apparently it seems that the output of get_town.php is JSON
echo json_encode($json);
but in your JS it is directly output to an html element
$('#town').html(html);
Solution:
Either modify get_town.php to send html OR modify the success function in JS to convert received JSON to proper html.
I hope this will help.
UPDATE:
Replace this part of php
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
}
with something
echo '<option value="" selected>Select Town</option>';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['town'].'" color="white">'.$row['town'].'</option>';
}
and finally remove the line
echo json_encode($json);
I am attempting to submit a form immediately after a selection is made from a drop-down menu. After the form is submitted I want to send a query to a MySQL database based on the selection from the drop-down and display the retrieved text.
Currently, with what I have below, nothing is displayed, no errors are thrown. The JS submit event handler works but after the page reloads the new text is not displayed.
Any help is greatly appreciated.
The JS for submitting the form:
$(".platformSelectDropDown").change(function() {
$('.platformSelectForm').submit();
});
PHP to run after the form is submitted:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$platform = $_POST['platformSelectDropDown'];
$description = call_data($tableName, $platform)['Description'];
$application = call_data($tableName, $platform)['Application'];
}
PHP Function for querying and returning the data:
function call_data($tableName, $col, $platformName) {
include('connection.php');
$sql = 'SELECT * FROM $tableName WHERE platform_name = $platformName';
try {
return $db->query($sql);
}
catch (Exception $e) {
echo "Error! " . $e->getMessage() . "<br/>";
return array();
}
}
The Form:
<form class="platformSelectForm" method="post" action="index.php">
<select name="platformSelectDropDown" class="platformSelectDropDown">
...
</select>
<ul class="indent">
<li><?php echo($description); ?></li>
<li><?php echo($application); ?></li>
</ul>
</form>
I believe the code below will do what you want, with some improvements in security and functionality. However, please note that it's not clear to me from your code where $tableName is being set, so I just hard-coded that to be my test table. I intermingled the php and html, because it made it easier for me to work through the problem and I think it will make it easier for you to follow my solution. There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. Check it out:
<html>
<body>
<form class="platformSelectForm" id="platformSelectForm" method="post">
<?php
// Get which dropdown option is selected, if any, so can keep selected on page reload
if(!isset($_POST['platformSelectDropDown'])) {
// Not postback, default to first option ("Select One")
$p0Select = ' selected';
$p1Select = '';
$p2Select = '';
} else {
// Is postback
// Set variables for query below
$tableName = 'tbl_platforms_1';
$platformName = $_POST['platformSelectDropDown'];
// set dropdown selection to whatever was select at form submission
if($platformName == 'Platform_1') {
$p1Select = ' selected';
} elseif ($platformName == 'Platform_2') {
$p2Select = ' selected';
} else {
$p0select = ' selected';
}
}
?>
<select name="platformSelectDropDown" class="platformSelectDropDown" onchange="document.getElementById('platformSelectForm').submit()">
<option value="Select_One"<?php echo $p0Select; ?>>Select One</option>
<option value="Platform_1"<?php echo $p1Select; ?>>Platform 1</option>
<option value="Platform_2"<?php echo $p2Select; ?>>Platform 2</option>
</select>
<?php
// If dropdown value is set and does not equal "Select_One"
if(isset($_POST['platformSelectDropDown'])&& $_POST['platformSelectDropDown'] != 'Select_One') {
?>
<ul class="indent">
<?php
try {
// Set database parameters
// Replace these values with appropriate values for your database
// (okay to use an include like you did originally)
$dbhost = 'your_database_host';
$dbname = 'your_database_name';
$dbuser = 'your_database_user';
$dbpass = 'your_database_user_password';
// Create PDO
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement and bind parameters
$stmt = $conn->prepare("SELECT * FROM $tableName WHERE platform_name = :platformName");
$stmt->bindValue(':platformName', $platformName, PDO::PARAM_STR);
// Execute statement and return results in an associative array (e.g., field_name -> value)
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close Connection
$conn = null;
// For each row that was returned, output results
for ($i = 0; $i < count($results); $i++) {
echo '<li>' .$results[$i]['Description'] .'</li>';
echo '<li>' .$results[$i]['Application'] .'</li>';
}
} catch (Exception $e) {
echo '<li>Error! ' .$e->getMessage() . '</li>';
}
?>
</ul>
<?php
};
?>
</form>
</body>
</html>
Code I used to setup test:
DROP TABLE IF EXISTS tbl_platforms_1;
CREATE TABLE IF NOT EXISTS tbl_platforms_1 (
id int AUTO_INCREMENT NOT NULL,
platform_name varchar(20),
Description varchar(20),
Application varchar(20),
PRIMARY KEY (id)
);
INSERT INTO
tbl_platforms_1
(platform_name, Description, Application)
VALUES
('Platform_1', 'Description 1', 'Application 1'),
('Platform_2', 'Description 2', 'Application 2');
If this solves your problem, please remember to mark as answered, so everyone will know you no longer need help (and so I'll get rewarded for the hour I spent coming up with this solution :-). If this doesn't solve your problem, please provide as much detail as possible as to how the current results differ from your desired results and I will try to revise it to fit your needs. Thanks!
I'm new with coding and I found some really valuable information that could help my register form look better using Ajax.
The problem is that, even though the php files are working fine, I think that the js file is not doing it's job. here:
in the register form there's this:
<?php
include 'php_includes/conexion.php'; (connect to DB users)
include 'php_includes/conexionlugar.php'; (connect to DB states/cities)
?>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.js"></script>
</head>
in the form there's this:
Select State
<select name="departamento" id="departamento">
<option value="">Seleccione Departamento</option>
<?php echo cargar_departamentos();?>
</select>
Select City
<select name="provincia" id="provincia">
<option value="">Seleccione Provincia</option>
</select>
Now, in the conexionlugar.php (tested/working):
<?php
function cargar_departamentos()
{
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output = '';
$sql = "SELECT * FROM departamentos ORDER BY NOMBRE_DEPA";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDDEPARTAMENTOS"].'">'.$row["NOMBRE_DEPA"].'</option>';
echo "$output";
}
}
return $output;
?>
in the jquery.js (don't know much about this :()
$(document).ready(function(){
$('#departamento').change(function(){
var IDDEPARTAMENTOS = $(this).val();
$.ajax({
url:'../php_includes/fetch_provincia.php',
type:"POST",
data:{departamentoId:IDDEPARTAMENTOS},
dataType:"text",
success:function(data)
{
$('#provincia').html(data);
}
});
});
});
in the fetch_provincia.php (tested/working)
<?php
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output ='';
$sql = "SELECT * FROM provincias WHERE departamentos_IDDEPARTAMENTOS = '".$_POST["departamentoId"]."' ORDER BY NOMBRE_PROV";
$result = mysqli_query($connect, $sql);
$output = '<option value="">Seleccione Provincia</option>';
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDPROVINCIAS"].'">'.$row["NOMBRE_PROV"].'</option>';
echo $output;
}
return $output;
?>
Though separately the PHP files are working, the JS file changing departamentoId for IDDEPARTAMENTOS looks like it's not... help me please.
I think I fixed it, deleting the "return" on both php and adding the js to the same page and not calling it through
The data you are sending from php needs to be sent as json. I would actually not do the "formatting" in php. Just return $result:
echo json_encode($result);
then in your js file, just iterate through "data" and create the options:
success:function(data)
{
$.each(data, function(key, val){
console.log("Key: " + key + " val: " + val);
}
}
have a some errors in your code.
First, in "cargar_departamentos", the return it´s out of a function, and in your fetch_provincia.php, not need a return statement.
In your jQuery code, try remove one of both jQuery called in your head, and Change de dataType directive of "text" to HTML.
#gilgameshbk you are calling jquery 2 times in your head
maybe this may cause some conflict.
I have a web program where the goal is plot data points for a certain Kiln that the user has selected. My problem is when a user wants to select a new Kiln, how can I update all the separate JSON pages to where the data is pulled from the new table they selected?
Here is my drop down list creater code.
<p class="navleft">
Kiln Number:<br>
<select name="kilns" id="kilns">
<?php
$sql = "SHOW TABLES FROM history";
$result = mysqli_query($con,$sql);
while($table = mysqli_fetch_array($result)) { // go through each row that was returned in $result
echo ("<option value='". $table[0] . "'>" . $table[0] . "</option>");
}
?>
</select>
</p>
And here is one of the php pages where I select all the data from a value in a table and turn it into a JSON file.
<?php
$con = mysqli_connect("localhost","KilnAdmin","KilnAdmin","history");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"history") or die ("no database");
//Fetch Data
$query = "SELECT * FROM k1_history LIMIT 1000";
$result = mysqli_query($con,$query);
if ($result) {
$data = array();
while($row = mysqli_fetch_assoc($result)) {
//$data[] = $row;
$data[] = array(
"date" => $row[ 'Timestamp' ],
"value" => $row[ 'DryBulbFront' ]
);
}
echo json_encode($data);
}
else {
echo "Error";
}
?>
Where is says k1_history, how can I get that to be the selection from the user in the dropbox menu from the other page?
In this kind of scenario you have to strongly pay attention to avoid SQL injection. Use a whitelist approach as mentioned by Konstantinos Vytiniotis and check this out How can I prevent SQL injection in PHP?
If I understand correctly what you want, then what you need is Ajax.
You have to populate the select like you do and on each select, make an Ajax call to a .php where you will handle what the user has chosen. In your case this .php file is going to take the table name the user chose, run a query and return some results back to the html. For demonstration purposes, I'll explain with an example.
Let's say in your .html you have a select like this:
Select Value:
<select name="kilns" id="kilns">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
What defined in the value property of the option is what you are gonna pass to the .php file I mentioned. To do that, you use Ajax, so inside some script tags you have:
$('#kilns').on('change', function(e) {
var data = {'kilns': this.value};
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
dataType: 'json'
}).done(function(msg) {
alert(msg);
});
});
What this does is that every time a user selects something from the select, then this function is called, where the select's value (var data = {'kilns': this.value};) is being sent to a file named submit.php, via POST. The submit.php could look like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$kilns_error = 0;
if (isset($_POST['kilns']) && !empty($_POST['kilns'])) {
$kilns = $_POST['kilns'];
} else {
$kilns = null;
$kilns_error = 1;
}
if ($kilns_error != 1) {
echo json_encode($kilns);
}
}
What happens here is after we check we have indeed a POST REQUEST, we check whether the value is undefined or empty. After this simple check, we proceed to echo json_encode($kilns); where we return the value that we initially sent to the .php script, which in fact is the value the user selected.
In your case, what you have to do it to actually do some things in the .php script and not just return the value that you called it with. Also, make sure to pass the value you take through a whitelist to ensure that the user selects an actual table and is not trying to create problems for your database, cause it would be really easy to just change the value of what he is going to select before actually selecting it. Have a look at the prepared statements of the mysqli and PDO.
Currently my dependent list is working on $_GET request. I'm trying to convert $_GET request to $_POST in Ajax without reloading the form. In the head I put #$cat=$_GET['cat']; I want this to be like $_POST and below ajax script is working on self.location which means its getting the value from $_GET url. I want the below script to work like $_POST and without reloading the form. Any help would very much appreciated.
my global declaration on the top as below
#$cat=$_GET['cat'];
my sql queries as below
<?php
# category and sub-category
$quer2="SELECT DISTINCT name,id FROM tblproductgroups order by name";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups where group_id=$cat order by sub_group_name";
}else{$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups order by sub_group_name"; }
?>
my ajax script as below
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='product-add.php?cat=' + val ;
}
function disableselect()
{
<?Php
if(isset($cat) and strlen($cat) > 0){
echo "document.myForm.subcat.disabled = false;";}
else{echo "document.myForm.subcat.disabled = true;";}
?>
}
</script>
my dependent drop down list as below
<?php
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
$sql = mysqli_query($customCon, $quer2);
while ($row = mysqli_fetch_array($sql)) {
if($row['id']==#$cat){echo "<option selected value='$row[id]'>$row[name]</option>"."<BR>";}
else{echo "<option value='$row[id]'>$row[name]</option>";}
}
echo "</select>";
echo "<select name='subcat'><option value=''>Select one</option>";
$sql2 = mysqli_query($customCon, $quer);
while ($row2 = mysqli_fetch_array($sql2)) {
echo "<option value='$row2[id]'>$row2[sub_group_name]</option>";
}
echo "</select>";
?>
Use jQuery (see their site for installation instructions) and add a change event handler to your select item. Also add an container div to your HTML code that will hold your dynamically loaded content like:
<div id="myCatContainer"></div>
In the event handler do:
$('#myCatContainer').load('product-add.php?cat=' . $('#mySelect').val();
Be sure to read about jQuery and how to define an event handler, before you try the above code!