How to link drop-down menu to table using ajax - javascript

I am trying to populate a html table based on the selection from drop-down menu. i.e. when I selected an option from drop-down menu, it shows a table having description of that selected item fetched from the database like it fetches a row of that value and shows it in a table.
Now for this, I have to use Ajax & Jquery but i don't know much about ajax.
Can you please help me this?
Here is my code:
$("#courses").change(function(){
var course = $(this).val();
$.ajax({
url:'your php page url',
type:'post',
data:'course='+course,
success:function(response){
// your drop down box is in response
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="courses" id="courses" class="dropdownclass" ><option selected="selected" value="" disabled selected hidden >-- Select an option --</option>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('db');
$sql = "SELECT courses FROM table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value=' " . $row['courses'] ."'>" . $row['courses'] ."</option>";
}
?>
</select>
I don't know what to add in ajax and where to put the table and link it with drop-down menu. Kindly help me with this.

Here is sample static code to implement your functionality. You can add your dynamic content using sql and php.
index.php
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="paragraph-div">
<select id="courses">
<option value="cource_1">Cource 1</option>
<option value="cource_2">Cource 2</option>
<option value="cource_3">Cource 3</option>
<option value="cource_4">Cource 4</option>
</select>
<table id="myTable" border="1">
</table>
</div>
</body>
</html>
<script type="text/javascript">
$("#courses").change(function(){
var course = $(this).val();
$.post('data.php', {course: course}, function(response){
// your drop down box is in response
$("#myTable").html(response);
});
});
</script>
data.php
<?php
$course = $_POST['course'];
// Fetch data from db related to $course
$html = '<tbody>
<tr>
<td>Course Name : </td>
<td>Course 1 </td>
</tr>
<tr>
<td>Course Description : </td>
<td>Lorem ipsum Lorem ipsum Lorem ipsum</td>
</tr>
</tbody>';
echo $html;
die();
?>
Hope now it's clear.

Related

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

how do i get the select value not the option value in php

Hi can some one help me to my problem.
I have a html and php function here all i want to to is to echoed a select value not the option value
here is my code
Ouput: Patrick or any for the name when I select and send the button
<?php if(isset($_REQUEST['send'])){echo $_POST['test'];}?>
<form method="post">
<select name="test"><option value="1">Patrick</option><option value="2">Maria</option><option value="3">Fe</option></select><input type="submit" name="send" value="submit">
</form>
specify the value in option like this "1_Patrick"
<?php if(isset($_REQUEST['send'])){
$value = explode('_',$_POST['test']);
echo $value[1];
}
?>
<form method="post">
<select name="test"><option value="1_Patrick">Patrick</option><option value="2_Maria">Maria</option><option value="3_Fe">Fe</option></select><input type="submit" name="send" value="submit">
</form>
<?php if(isset($_REQUEST['send'])){echo $_POST['test'];}?>
change the value of your option to you want to display
<form method="post">
<select name="test">
<option value="Patrick">Patrick</option>
<option value="Maria">Maria</option>
<option value="Fe">Fe</option>
</select>
<input type="submit" name="send" value="submit">
</form>
//change the $row['id'] to $row['name']
<?php $q = mysql_query("select * from name");?>
while($row = mysql_fetch_assoc($q)){
echo '<option value='.$row['name'].'>'.$row['name'].'</option>' ;
}
// ok you want to used the id in option value.in your submit code get the name for table check bellow code
<?php if(isset($_REQUEST['send'])){$id=$_POST['test'];
$q = mysql_query("select * from name where id=$id");
$row = mysql_fetch_assoc($q);
echo $row['name'];
}
?>
<?php $q = mysql_query("select * from name");
while($row = mysql_fetch_assoc($q)){
echo '<option value='.$row['id'].'>'.$row['name'].'</option>' ;
}?>
The value of the select will be whatever option is selected. If I select Maria, you will see 2 displayed.
<table cellpadding="3" cellspacing="3" align="center" width="50%">
<tr>
<td>
<select name="user" id="user_id" onChange="selectuser()">
<option value="0">Select User</option>
<option value="1">Patrick</option>
<option value="2">Maria</option>
<option value="3">Fe</option>
</select>
</td>
</tr>
</table>
<script language="javascript">
function selectuser()
{
var name = $("#user_id option:selected").text();
alert(name);
}
when you post any form then data contained in the value attribute of the field will get posted.
So you can change the value data to the desired value, like value="Patrik"
As you said that there is purpose behind adding numeric data to value then my suggestion would be add this numeric data to some other custom attribute like data-customid="1" etc and change value="Patrick"
You can add custom attribute in option value.
Refer this link for details.
pure js:
DEMO
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('select').addEventListener('change', function() {
alert(this.options[this.selectedIndex].innerText);
}, false);
}, false);

Jquery chosen plugin doesn't Work in ajax response

I have two select box. and I want to apply chosen plugin in both select box.
When No-1 Select box change then No-2 select box generate from AJAX response.
Chosen Plugin in No-1 work perfectly. But When No-2 select box generate from ajax then chosen plugin doesn't work in No-2 select box.
main.php
<tr>
<td>Select Location</td>
<td>
<select id="issue_type" name="issue_type" class="chosen-select">
<option value="" disabled="disabled" selected="selected">Select Location</option>
<option value="17">RM Store</option>
<option value="17">PM Store</option>
<option value="17">FG Store</option>
</select>
</td>
</tr>
<tr id="tr_product" name="product">
<td>Select Product</td>
<td></td>
</tr>
JS code for ajax
$('#location').change(function(){
if(this.value){
$('#td_avail_qty').html('');
$.ajax({
type:"GET",
url:"mat_issue.php",
data:{action:"ajax",sub_action:"location",location:this.value}
}).done(function(data){
$('tr#tr_product').show().children().eq(1).html(data);
});
}
});
mat_issue.php
$product_str = '<select id="product" name="product" class="chosen-select">
<option value="" disabled="disabled" selected="selected">Select Product</option>';
$location = $req['location'];
$sql_product = "SELECT l.`loccode`, l.`stockid`, l.`quantity`,s.description FROM `locstock` l INNER JOIN stockmaster s ON l.stockid = s.stockid WHERE l.`loccode` = '$location' AND l.`quantity` > 0";
if($query_fg = DB_query($sql_product,$db)):
while($data_product = DB_fetch_assoc($query_fg)):
$product_str .= '<option title="Available Quantity '.$data_product['quantity'].'" value="'.$data_product['stockid'].'">'.$data_product['description'].'</option>';
endwhile;
endif;
$product_str .= '</select>';
echo $product_str;
No-2 Select box generate from ajax successfully. But chosen plugin doesn't work in this select box.
I use this code for chosen plugin
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
And I use .chosen-select class in my select box
pass your chosen jquery function in your ajax success function...
may be this can help you out..
$('#location').change(function(){
if(this.value){
$('#td_avail_qty').html('');
$.ajax({
type:"GET",
url:"mat_issue.php",
data:{action:"ajax",sub_action:"location",location:this.value}
}).done(function(data){
$('tr#tr_product').show().children().eq(1).html(data);
$("#product").chosen({max_selected_options: 5}); //your chosen code for select tag
});
}
});
let me know if you face any other problem....
You need to load chosen after you have finished loading data in the select tag, Look at my snippet below
<script>
$('#subject_id').on('change',function(e){
var subject_id = e.target.value;
$.get('/ajax_subject_finder/'+subject_id,function(data){
$('#subject_paper_id').empty();
$('#subject_paper_id').append("<option></option>");
$.each(data,function(index,subObject){
$('#subject_paper_id').append("<option value="+subObject.id+">"+subObject.number+"</option>");
});
$('#subject_paper_id').chosen();
});
});

How to pass parameter as POST data on selection of an Select Box value, which will reload the same page?

I had two chained Select Boxes "pr_cat" and "sl_num" . The second select box values depend on the value selected in the first select box.
<tr>
<td width="257">Select Product Category:</td>
<td width="197">
<select name="pr_cat" id="Validprcat" onChange="reload(this.form)"><option value="">< Select one ></option>
<?php while($prd=mysql_fetch_object($select_query1)) {
if ($prd->cat_id==$pcat) { ?>
<option selected value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?> </option>
<?php } else { ?>
<option value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?></option>
<?php }}?>
</select>
</td>
</tr>
<tr>
<td>Select Serial Number:</td>
<td>
<select name="sl_num" id="Validslnum" onChange="reload2(this.form)"><option value="">< Select one ></option>
<?php while($slnum=mysql_fetch_object($quer)) {
if ($slnum->serialno==$pcat2) { ?>
<option selected value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?> </option>
<?php } else {
?>
<option value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?></option>
<?php }} ?>
</select>
</td>
</tr>
<tr>
I used the form reload javascript to reload the page with the value selected in the Select Box. I used GET method.
<script language=JavaScript>
function reload(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val ;
}
function reload2(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
var val2=form.sl_num.options[form.sl_num.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val + '&pcat2=' + val2 ;
}
</script>
But I want to do it using POST method how to do this ?
If you don't want to use ajax, and do it via POST method, so instead of
onChange="reload(this.form)"
call
onChange="formSubmit();"
<script>
function formSubmit()
{
document.getElementById("frm1").submit(); //frm1 is form id
//OR you can use
//document.frm1.submit(); //frm1 is form name
}
</script>
Note :- if you have any submit button in this form, don't keep it's name as submit, else you will have issues in your code.
I think what you're asking is pretty much this: JavaScript post request like a form submit
However, why do you want to reload the page at all instead of doing an AJAX call?
I give you the most simple and fastest way to do what you wanted,
AJAX:
cover both select box with '' tag,
<div id='first_select'>
<select id='first' onchange='populate_second_select(this.value)'>
<option>Select</option>
</select>
</div>
<div id='second_select'>
<select>
<option>Select</option>
</select>
</div>
call populate_second_select() function upon change done in first select box.
No in ajax,
function populate_second_select(value)
{
$.ajax({
method:'POST',
url:'ajax.php',
data: {value:value},
success:function(result)
{
document.getElementById("second_select").innerHTML=result;
showLightBox();
}
});
}
This is how your javascript function should look like,
on your ajax.php file, process the DB based on chosen value and 'echo' the whole select tag (second tag). That's it.
Here are few links would help you to get this done.
Link_1Link_2

Values not inserting into database table

I am trying to insert the values from drop-down and text box throug web page.
first there will be one drop down box that has numbers from 1 to 25..
when i select the number from the dropdown, the corresponding textboxes and dropdown boxes are created.
But when i enter the data and click the submit button,the values are not going to database, instead only the last row values are inserting into database.
for example:
say i have selected 4 from number dropdown, now 4 rows with textbox and dropdown box appears.
when i enter the data in the textbox and select value from dropdown and click submit. the last row values are getting inserted 4 times.
i want it to insert the values correctly...How can i solve this.?
here is the code i am using..
code:
<html>
<head>
<link rel="stylesheet" href="css/common.css" type="text/css">
<link rel="stylesheet" type="text/css" href="css/page.css">
<link rel="stylesheet" type="text/css" href="css/button.css">
<link href="css/loginmodule.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type='text/javascript' src='js/jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#Fname").autocomplete("get_course_list.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
});
</script>
<script>
function showUser(str) {
if(str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gettheater.php?q="+str,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
target.innerHTML = '<input name="RowCount" value="' + param + '" hidden />';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. " </option>";
}
echo "</select>";
?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
</script>
<style>
#screens{
color:black;
}
</style>
</head>
<body>
<h1>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
My Profile | Logout
<p>This is a password protected area only accessible to Admins. </p>
<center>
<div class="pan"><br><br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" autocomplete="off">
<div class="head">Update Theater Information</div>
<table>
<tr>
<td><label for="screens">New Movies Released</label></td>
<td>
<select id="select" onchange='javascript:create(this.value);' name="range">
<option>--Select Number Of New Movies Released--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<div id="screens">
</div>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="button" name='submit' value="Submit" /></td>
</tr>
</table>
</form><br><br>
</div>
<?php
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
for ($i=0; $i < $_POST["range"] ; $i++)
{
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
}
?>
</center>
</body>
</html>
You should change you name to array like
target.innerHTML += '<input type="text" name="Fname[]">';
And also in insert query should be
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname'][$i]."','".$_POST['language']."') ") or die(mysql_error());
1.Use mysqli_* function instead of mysql_* function...
2. What is error showing up.
If you have insertion query on same page then try it:.....
<?php
if(isset($_POST['submit'])
{
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
for ($i=0; $i < $_POST["range"] ; $i++)
{
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
}
}
?>
It will triger your query when submit button will hit.... may this help
Use this
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname']."','".$_POST['language']."') ") or die(mysql_error());
instead of
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
You must keep php code outside of quote and Concate them
2.If The index of $_POST Array is string then it must be with quote. (e.x: $_POST[language] it must be $_POST['language']
Thank god....I resolved My issue.....i used the same logic that was applied to first text box...
and now the dropdown values are also getting inserted....
i added array to language[]
echo "<select name='language[]' id='course'>";
and added the $i in loop
.$_POST['language'][$i]
Thanks all for helping me.....
HaPpY CoDiNg....
I don't want to be an ass, but I would suggest cleaning things up and seperating the JavaScript, jQuery and PHP even loose JavaScript AJAX and use jQuery AJAX. It's no surprise code like this is giving you bugs.

Categories

Resources