How to POST two parameters in PHP using Ajax - php

I want to pass two parameters into the function getStuName() but found that there is error. Can anyone help me with the syntax?
<script language="javascript">
function getStuName1(val, val1) {
if(val!=''){
$.ajax({
type: "POST",
url: "get_stuname1.php",
data:'yr='+val+'&classname='+val1,
success: function(data){
$("#stu-list1").html(data);
}
});
alert(data);
}else{
document.getElementById('stuname').options.length=1;
document.getElementById('stuname').options[0].text='Please select';
}
} //end function
</script>
<select style="font-size: 18px;" name="yr" onChange="getStuName1(this.value);">
<option value="2021-2022">2021-2022</option>
<option value="2022-2023">2022-2023</option>
<option value="2023-2024">2023-2024</option>
<option value="2024-2025">2024-2025</option>
<option value="2025-2026">2025-2026</option>
<option value="2026-2027">2026-2027</option>
</select>
<select style="font-size: 18px;" name="classname" id="class-list" class="demoInputBox" onChange="getStuName1(this.value);">
<option value="" selected>please select</option>
<?php
$sql="SELECT classname FROM class";
$class_result = mysqli_query($db_link,$sql);
while($rs = mysqli_fetch_array($class_result, MYSQLI_ASSOC)) {
?>
<option value="<?php echo $rs["classname"]; ?>"><?php echo $rs["classname"]; ?></option>
<?php
}
?>
</select>
Content of get_stuname1.php
<?php
require_once("connMysql.php");
$sql_stu ="SELECT * FROM stu_hist WHERE enabled='1' AND sch_yr = '" . $_POST['yr'] . "' AND classname = '" . $_POST['classname'] . "' ORDER BY classno";
$stu_result = mysqli_query($db_link,$sql_stu);
while($rs = mysqli_fetch_array($stu_result, MYSQLI_ASSOC)) {
?>
<option value="<?php echo $rs["stu_name"]; ?>"> <?php echo $rs["stu_name"]; ?></option>
<?php
}
?>
I want to get the yr and classname and pass them into the function getStuName1 but cannot display student name

To ensure that the values from both select menus ( or all if there are more ) are used in the ajax request one method you might consider would be to use a global variable that you populate when a select menu triggers the change event. This global variable could be an object or array - it is the effective length when populated that is of interest as we can decide to send the AJAX request only when both/all select menus have been changed. This is all done without jQuery but the fetch code could very easily be replaced with suitable jQuery code. No need for buttons to fire the request...
// populate this with select name & value pairs
let args={};
// a function to process the response from the server
let callback=(r)=>{
document.getElementById('stu-list1').innerHTML=r;
}
// delegated event handler bound to the document
document.addEventListener('change',e=>{
if( e.target instanceof HTMLSelectElement && e.target.classList.contains('required') ){
// store this select menu name/value
args[ e.target.name ]=e.target.value;
// if BOTH (all) select menus are populated, do the AJAX request
if( Object.keys( args ).length==document.querySelectorAll('select.required').length ){
let payload=Object.keys( args ).map(name=>{
return [ name, args[name] ].join('=')
}).join('&');
fetch( 'get_stuname1.php', { method:'post', body:payload } )
.then(r=>r.text())
.then(callback)
.catch(alert)
}
}
});
<select name="yr" class='required'>
<option selected hidden disabled>please select...
<option>2021-2022
<option>2022-2023
<option>2023-2024
<option>2024-2025
<option>2025-2026
<option>2026-2027
</select>
<select name="classname" id="class-list" class="demoInputBox required">
<option selected hidden disabled>please select...
<option>geronimo
<option>horatio
<option>mimosa
</select>
<div id='stu-list1'></div>

Since you are passing two parameters to the getStuName1 function, so instead of using onChange (for a change in one select box) , it is recommended that you have a button which submit the two selected values when both of the them are selected (a "confirm submission" button is the preferred choice because normally a person needs to make up his/her mind that all the select boxes are properly chosen before the actual submission, and actually there is no point to trigger the ajax if only one of the select boxes are selected)
Hence
make sure that both select box are having a unique id (so add id="yr" for the yr select box)
add say a button which trigger passing the selected values of the two select boxes, such as:
<input type=button value="Confirm" onclick="javascript:trigger1();">
and
<script>
function trigger1() {
var e = document.getElementById("yr");
var value1 = e.value;
var e2 = document.getElementById("class-list");
var value2 = e2.value;
getStuName1(value1, value2);
}
</script>
So, change your code to
<script language="javascript">
function getStuName1(val, val1) {
if(val!=''){
$.ajax({
type: "POST",
url: "get_stuname1.php",
data:'yr='+val+'&classname='+val1,
success: function(data){
$("#stu-list1").html(data);
}
});
alert(data);
}else{
document.getElementById('stuname').options.length=1;
document.getElementById('stuname').options[0].text='Please select';
}
} //end function
</script>
<select style="font-size: 18px;" name="yr" id="yr">
<option value="2021-2022">2021-2022</option>
<option value="2022-2023">2022-2023</option>
<option value="2023-2024">2023-2024</option>
<option value="2024-2025">2024-2025</option>
<option value="2025-2026">2025-2026</option>
<option value="2026-2027">2026-2027</option>
</select>
<select style="font-size: 18px;" name="classname" id="class-list" class="demoInputBox" >
<option value="" selected>please select</option>
<?php
$sql="SELECT classname FROM class";
$class_result = mysqli_query($db_link,$sql);
while($rs = mysqli_fetch_array($class_result, MYSQLI_ASSOC)) {
?>
<option value="<?php echo $rs["classname"]; ?>"><?php echo $rs["classname"]; ?></option>
<?php
}
?>
</select>
<input type=button value="Confirm" onclick="javascript:trigger1();">
<script>
function trigger1() {
var e = document.getElementById("yr");
var value1 = e.value;
var e2 = document.getElementById("class-list");
var value2 = e2.value;
getStuName1(value1, value2);
}
</script>
[Additional point]
Last but not least, please amend your PHP script to use parameterized prepared statement which is resilient against SQL injection. You may refer to the following:
For Mysqli:
https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
For PDO
https://www.php.net/manual/en/pdo.prepare.php

Related

Showing content in select box base on previous select box

hello developer community.I need your help.i am building a project on attendance management.In this project,i got stucked on one feature.
what i want is to display the departments based on the block input without going to next page.
<div class="form-group">
<label for="block" class="control-label col-sm-2">Select block:</label>
<div class="col-xs-10">
<select class="form-control" name="block" id="block">
<option selected="selected" value="">Select Block:</option>
<?php
$q="select * from blocks ORDER BY block_name";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[block_id]'class='form-control'>".$row['block_name']."</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="department" class="control-label col-sm-2">Select department:</label>
<div class="col-xs-10">
<select class="form-control" name="department" id="department">
<option selected="selected" value="">Select Department:</option>
<?php
$q="select * from departments ORDER BY department_name";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[department_id]'class='form-control'>".$row['department_name']."</option>";
}
?>
</select>
</div>
Create a PHP file, e.g. dep-getter.php
<?php
// Include your connection config
include 'db-config.php';
// getting block value
$block = $_GET['block'];
$where = !empty($_GET['block']) ? "block='$block'" : '1=1';
$q="select * from departments ORDER BY department_name WHERE $where";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[department_id]'class='form-control'>".$row['department_name']."</option>";
}
?>
JavaScript/jQuery:
$(document).ready(function() {
$('.block-select').change(function() {
var val = $(this).val();
$.ajax({
url: '/path/to/dep-getter.php?block='+val,
method: 'GET',
success: function(data) {
$('.select-department').html(data);
},
error: function() {
console.log('Something went wrong!');
}
});
});
});
I use the before code for simple understanding. For detail explaination, you can read Ajax documentation.
Note:
You need adding class to Department select option with name select-department as a target to put ajax result.
Hope this help you.
The best way I think is using Ajax.
But if you don't know about Ajax yet, the idea is to reload the current page with appending query string with Block value, and then show the Department base on block value.
So, for getting block value and reloading you can use jQuery for simple way.
The code come like this.
The Block select option (adding class for selector):
<select class="block-select">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
JavaScript/jQuery:
$(document).ready(function() {
$('.block-select').change(function() {
var val = $(this).val();
var curUrl = window.location.href;
// Append the value to current URL & reload
var targetUrl = curUrl + '?block=' + val;
window.location.href = targetUrl;
});
});
And then change your Department select option to like this:
<select class="form-control" name="department" id="department">
<?php
$where = !empty($_GET['block']) ? "block='$_GET[block]'" : '1=1';
$q="select * from departments ORDER BY department_name WHERE $where";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[department_id]'class='form-control'>".$row['department_name']."</option>";
}
?>
</select>
The above code will checking for block value from URL, if the block not empty then we will get department data by block value, otherwise get all.

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>

AJAX DropDown not populating

I am using Jquery and PHP. So that on selection of first dropdown the value of first drop down should be passed to a Mysql query and then populate the second dropdown, but the second drop down displays blank.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#city").change(function() {
var value = $(this).val();
$.ajax({
type : "GET",
url : 'abc.php',
data : {
choice : value
},
success : function(data){
$('#123').html(data);
}
})
});
});
</script>
<form action="" method="post">
<select class="form-control" id="city" action="" name="city" value="">
<option value="">--</option>
<option value="1"</option>
<option value="2"</option>
<option value="3"</option>
</select>
<br/>
</div>
<div class="form-group">
<select class="form-control" action="" name="123" id="123"">
<option value="--">--</option>
<?php
$query = "SELECT DISTINCT `Comm` FROM `Comm_New` WHERE `Market`='".$_GET['city']."' ORDER BY `Comm` ASC";
if ($result = mysqli_query($link, $query)) {
while ($Comm = mysqli_fetch_assoc($result)) {
print_r("<option value='".$Comm['Comm']."'>".$Comm['Comm']."</option>");
}
}
?>
</select><br/>
</div>
From our conversation in the comments you are calling the same page that you are originally loading. That is not necessarily a problem technically, it's just not implemented properly. To load the same page, you need to do:
<?php
// Make sure your database is initiated above here so this can use it.
// I am going to demonstrate a basic binding using a super basic PDO
// connection because procedural mysqli_* with bind is just annoying
$link = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Notice that you send "choice" as the GET key in your ajax, not "city"
if(!empty($_GET['choice'])) {
?>
<select class="form-control" action="" name="123" id="123"">
<option value="">--</option>
<?php
// prepare, bind, execute here
$query = $link->prepare("SELECT DISTINCT `Comm` FROM `Comm_New` WHERE `Market` = :0 ORDER BY `Comm` ASC");
$query->execute(array(':0'=>$_GET['choice']));
// PDO has a lot of connection settings where you can set the default
// return type so you don't need to tell it to fetch assoc here.
// Also, you would tell the the connection not to just emulate bind
// etc.. I would consider using PDO or the OOP version of mysqli
while ($Comm = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='".$Comm['Comm']."'>".$Comm['Comm']."</option>";
}
?> </select>
<?php
// Stop the page from running further
die();
}
?><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#city").change(function() {
var value = $(this).val();
$.ajax({
type : "GET",
url : 'abc.php',
data : {
choice : value
},
success : function(data){
// Populate the empty container #new_drop
$('#new_drop').html(data);
}
})
});
});
</script>
<form action="" method="post">
<select class="form-control" id="city" action="" name="city" value="">
<!--
Your options are malformed. Missing close ">"
probably just copy error
-->
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br/>
</div>
<!-- Add id="new_drop" to this div -->
<div class="form-group" id="new_drop">
</div>
Ideally you want to have the top part on a new page, and possibly return a set of data as opposed to straight html, but ajax is very flexible.

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

passing dropdown seleect option to the url using javascript

passing dropdown selevect option to the url using javascript and it is working fine but problem is that <option>Select</option> also passing to the url now how could i disabled <option>Select</option> while passing the select option values to the url? i want to send only name to the url except <option>Select</option>?
function getComboC(sel) {
var name=document.getElementById("name");
var input_val = document.getElementById("name").value;
name.action = "searchexpense.php?name="+input_val+"";
name.submit();
<form name="name" id="name"><select class="select10"
name="pname" id="name" style="width:150px;" onChange="getComboC(this)">
<option value="0"><--Select--> </option>
<?php
$query=mysql_query("SELECT pname from expenses order by id");
while($row=mysql_fetch_assoc($query))
{
$val2=$row['pname'];
?>
<option value="<?=$val2;?>" <? if ($_GET['pname'] == $val2)
{ echo "selected='selected'"; }?> >
<?=$row['pname'];?>
</option>
<?php }?>
</select></form>
Url While Select <option>Select</option>
searchexpense.php?pname=0
Dynamically Option Select
searchexpense.php?pname=Test
you arr using same id for multiple elements, like for form and select. id's must be unique, so try:
<form name="my_frm" id="my_frm">
<select class="select10" name="pname" id="name" style="width:150px;" onChange="getComboC(this)">
....
and js function :
function getComboC(sel) {
//do not submit if default "select" is selected
if( sel.value != "0" ) {
var selected_value = sel.value; //selected dropdown value
document.my_form.action = "searchexpense.php?name="+selected_value;
document.my_form.submit();
}
}

Categories