How to pass database value to a dynamically added dropdown field - javascript

I have a page called new_booking.php and a page called addmore.php, i required the addmore.php inside the new_booking.php,When i click on the add more button it adds a dynamic drop down field. here snapshot of my code
</DIV>
<SCRIPT>
function addMore() {
$("<DIV>").load("addmore.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
Now the problem is when i click on the add more button it just add a text field without the value from database in a drop down.here is a snapshot of my addmore.php code
<DIV class="product-item float-clear" style="clear:both;"> <DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV > <select class = "mdl-textfield__input" id="categories" name="roomtype[]" >
<option value="">Choose Room Type</option>
<?php
$resultUser = mysqli_query($conn, "SELECT * FROM room_type ");
//$NoRowStaff = mysqli_num_rows($resultStaff);
if ($resultUser->num_rows > 0)
// Loop through the query results, outputing the options one by one
while($row = $resultUser->fetch_assoc()) {
echo '<option value="'.$row['rt_id'].'">'.$row['type'].'</option>';
}
?>
</select></DIV> <br><br>
<DIV> <select class = "mdl-textfield__input" name="roomno" id="subcat" required>
<option value="" selected>Choose Room number.... </option> </select></DIV>
</DIV>
How do i get to Append the value from the database to the newly added drop-down field, so that anytime i click on the addmore button it comes with value from database?

The way you are trying to complete this task will not work..because as far as i can understand your code, you are trying to call a php function within a javascript function.
What you can do is to implement a ajax function.
https://www.w3schools.com/xml/ajax_intro.asp
the process will look like this:
1. An event occurs in a web page (a button is clicked)
2. The Ajax object sends a request to a web server
3. The server processes the request (like get value from database)
4. The server sends a response back to the web page
6. The response is read by JavaScript
and after this you can append this value dynamically to your options :)
As Requested per Comment a simple Demo
http://crisscrosscrass.epizy.com/ajaxexample.php
code ajaxexample.php
<body>
<div id="" class="App-header">
<h1>This is an AJAX Example</h1>
<button onClick="addMore()">Add more </button>
<div id="output">
<div>
</div>
<script>
function addMore(){
$.ajax({
type: "POST",
url: "addmore.php",
// data: data, <--- in case you want also send some data to the server like Username etc.
success: function(data) {
$("#output").append(data);
},
error: function(){
// will fire when timeout is reached
$("#output").html("<h1>connection to the server failed!</h1>");
},
timeout: 1200
});
}
</script>
</body>
code addmore.php
<?php
//here you need to put you function for calling the database and return the values that you need
echo "Calling DatabaseRandom Value " . (rand() . "<br>");
?>

Related

select2 not letting my other scripts work

Sir, my ajax isnt loading when i use select2 plugin .
it works fine when i remove it. the blur event is working.
but i want to be able to search in the dropdown, and somehow ajax isnt working
this part isnt working
$("#bank_id").focus();
so due to above script not working the blur event in the code below isnt working.
this is the script and html
<div class="col-md-6">
<div class="form-group">
<label>Bank<span><font color="red"></font></span></label>
<select class="form-control select2" name="bank_id" id="bank_id">
<c:choose>
<c:when test="${bankDetailsEdit.bank_id != 0}">
<option value="${bankDetailsEdit.bank_id }" >${bankDetailsEdit.bankName }</option>
</c:when>
<c:when test="${bankDetailsEdit.bank_id == 0}">
<option disabled selected>Select Bank</option>
</c:when>
</c:choose>
<c:forEach var="bank" items="${bankMasterDetails}">
<option value="${bank.bank_id}">${bank.bank_name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Bank Branch Name<span><font color="red"> </font></span></label>
<select class="form-control select2" name="bankBranchId" id="op1" >
<option value="${bankDetailsEdit.bankBranchId }" >${bankDetailsEdit.bankBranchName }</option>
<c:forEach begin="0" end="100" varStatus="loop">
<option></option>
</c:forEach>
</select>
</div>
</div>
<script>
$('.select2').select2();
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#bank_id").focus();
$("#bank_id").on('blur change',function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var bank_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'bank_id':bank_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/bankBranchDetails",
data : ({
'bank_id':bank_id
}),
success: function (bankList) {
$('#op1').empty();
var opt = '<option disabled selected>Select Branch</option>';
for (var i = 0; i < bankList.length; i++) {
$('#op1').append(opt);
opt = new Option(bankList[i].bank_branch_name,bankList[i].bank_branch_id);
}
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
$("#op1").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var branch_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'branch_id':branch_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/branchIfscDetails",
data : ({
'branch_id':branch_id
}),
success: function (data) {
var ifsc = data;
document.getElementById("ifsc").value=ifsc;
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
});
</script>
From this page: https://select2.org/programmatic-control/events:
Select2 has an internal event system that works independently of the
DOM event system, allowing adapters to communicate with each other.
You are tied to using the plugins event handling mechanism so the first paremeter of the jQuery on function needs to be changed.
from $("#bank_id").on('blur change',function(){
to $("#bank_id").on('select2:select',function(){
Unfortunately $("#bank_id").focus(); will not work because it is not listed in the available select2 events.
You're success callback function in the first event listener, which tries to generate options element for the 2nd select box will also not work as select2 has a different way of adding options dynamically through AJAX as listed in this page: https://select2.org/data-sources/ajax
You need to use $('#bank_id').select2('open'); instead of $("#bank_id").focus(); to open the bank selection on page load.
You can check their documentation.

use ajax/js to update one of multiple select tags

I am running into a roadblock when attempting to use JavaScript to update a <select> tag on a page that I am creating. The issue I have is that this is a management style page, so there are multiple forms on one page, each one generated through PHP for an entry in a SQL database. For a better understanding of what I am talking about, here is some code from my project:
<?php
$query = "SELECT * FROM tableA ";
$data = $PDOcon->query($query);
$rows = $data->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$head = $row['head'];
$cont = $row['content'];
$app = $row['Product'];
$category = $row['CatID'];
Print "<form class='mgmt-ListView-Tall' action=\"#Anchor$id\" method=\"post\" width=\"60%\">
<input type=\"hidden\" name=\"id\" value=\"$id\" readonly />
<label for='pHead'>Heading: </label>
<input id='pHead' class='lbl-w25' name='pHead' value='$head' />
<label for='pCont'>Content: </label>
<input id='pCont' class='lbl-w20' name='pCont' value='$cont' />
<label for='pProd' >Product: </label>
<select id='pProd' name='pProd' class='pProd'>
<option value='0'>Product 1</option>
<option value='1'>Product 2</option>
</select>
<label for='pApp'>Application: </label>
<select id='pApp' name='pApp' class='pApp'>
</select>
</select>
<span><input class='mgmt-Button' id='editbtn' type=\"submit\" name='edit' value='Edit' /></span>
</form>";
}
?>
<script type="text/javascript">
$('.pProd').change(function(){
var string = this.value + ',' + '-1';
$.ajax({
url: 'scripts/get_app.php',
type: 'POST',
data: {get_option:string},
success:function(data){
document.getElementById('pApp').innerHTML=data; //This updates the select tag in the first form on the page, not the same form that the user was making changes in.
}
});
});
</script>
I have a table (TableB) that contains a list of all applications linked with their product, and what I am attempting to do currently is set up the page so that if the user changes the product in the select field on one of the forms that is generated, the application select tag is updated through AJAX. I am able to get it to update the first form on the page using document.getElementById, but I need it to update the tag with that id that is in the same form as the select tag the user was modifying (example: user makes a change to the pProd tag in the 4th form, the pApp tag in the 4th form gets updated)
I have attempted to call $(this).next(".pApp").innerHTML=data;, but this does not appear to find the tag with the correct class. I have also tried using closest() and sibling() to no avail. I have also tried referencing both id, and class with the same results, and I have searched around and could not find any solution to a problem similar to this. Does anyone have any suggestions?
The id attribute needs to be unique:
The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).1
So one solution is to append $id to the id attributes of the select lists.
<label for='pProd$id' >Product: </label>
<select id='pProd$id' name='pProd' class='pProd'>
<option value='0'>Product 1</option>
<option value='1'>Product 2</option>
</select>
<label for='pApp$id'>Application: </label>
<select id='pApp$id' name='pApp' class='pApp'>
Then in the AJAX updater, parse out that value for $id using String.replace():
$('.pProd').change(function(){
var id = this.id.replace('pProd','');
var string = this.value + ',' + '-1';
$.ajax({
url: '<?php echo $_SERVER['PHP_SELF'];?>',
type: 'POST',
data: {get_option:string},
success:function(data){
document.getElementById('pApp'+id).innerHTML=data; //This updates the select tag in the first form on the page, not the same form that the user was making changes in.
}
See it demonstrated in this phpfiddle.
Additionally, since jQuery is being used, the id selector and html() could be used to update the second select list:
success:function(data){
$('#pApp'+id).html(data);
}
1https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

Ajax filter: Select + Radio button

i have problem with this script:
When I select a type from the select and choose the amount of the radio buttons, the value does not change, but if I choose a new type from the select, then the value is altered properly.
I wish that once you choose a type from the select, changing several times the amount, the price value change in real time.
Thank you in advance
HTML + PHP
<select name="tipo" id="tiposelect">
<option selected="selected"> --- </option>
<?
$sql_tipo = mysql_query("SELECT * FROM AM_Tipi_Prodotto_Agenzia WHERE id_prodotto = $id_prodotto");
while($row_tipo = mysql_fetch_array($sql_tipo)){
?>
<option value="<?=$row_tipo['nome_prodotto']?>"><?=$row_tipo['nome_prodotto']?></option>
<? }?>
</select>
</div>
<div class="point-of-action">
<h5>Quantità:</h5>
<?
$sql_quantita = mysql_query("SELECT * FROM AM_Quantita_Prodotti_Agenzia WHERE id_prodotto = $id_prodotto LIMIT 3");
while($row_quantita = mysql_fetch_array($sql_quantita)){
?>
<input type="radio" name="quantita_2" value="<?=$row_quantita['quantita']?>"> <?=$row_quantita['quantita']?>
<? }?>
</div>
AJAX
<script>
$(document).ready(function () {
//RADIO BUTTON
$("input[name='quantita_2']").change(function() {
var value=$("input[name='quantita_2']:checked").val()
//SELECT
var tipo;
$("#tiposelect").change(function(){
tipo = $('#tiposelect').val();
$.ajax({
method: "POST",
url: "calcolo_agenzia.php",
data: { id_prodotto: <?php echo (isset($_REQUEST['id_prodotto']) ? $_REQUEST['id_prodotto'] : 0) ; ?>, quantita: value, tipo: tipo },
success: function( msg ) {
$("#importoCalcolato2").text("€"+msg);
}
});
});
});
});
</script>
FORM IMAGE
try changing $("#tiposelect").change(function(){ to $("#tiposelect").click(function(){ this will triger event every time toy click on $('#tiposelect')
Additionally you can also add another event handler to for $('#tiposelect').click() so that which ever changes will trigger ajax
Try following code
$("input[name='quantita_2']").on("change",function() {
//your code
}
Update:
check your tipo variable. It gets value only on change event of select. It's initial value should be the value of selected option.

Using Jquery to change form based on user input

I have a form with a select tag. I need my form to change based on the selection from the user. I am given to believe that the easiest way to do this is to use JQuery.
Here is my code:
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
</div>
<div id="addhtml"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
alert("event triggered");
var val = $(this).val();
if (val == "number" || val == "symbol") {
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
} else if (val == "letter") {
$("#addhtml").html(<?php include("html/form_letter.html"); ?>);
} else {
$("#addhtml").html(<?php include("html/form_other.html"); ?>);
}
});
});
</script>
Note: the php while statement just sets up the current three options of "number", "symbol" or "letter" with ids of 1,2 and 3 respectively
When I change the category, it does not trigger the jquery.change()
I would like to code the form without using the addhtml div but am willing to use it if necessary.
Questions:
Is the reason the change function is not being triggered because I am using php to set the values of the select options?
If so how can I resolve?
If not, why isn't it being triggered?
How can I accomplish my goal of not using the addhtml div?
Is there a better way to accomplish what I am going for?
Thanks in advance.
EDIT:
Answers to initial questions: As stated by bistoco, php is pre compiled by the server and sent in as html so the issue is not from using php to set the values of the select tag.
I have now determined that it is due to the content of my php include files. I have determined that it registers the change event and loads the content just fine if my file is simple like this:
"<div><label>New Number</label></div>"
but if I add any white space or \n characters for human readability like this:
"<div>
<label>New Number</label>
</div>"
Not only does it not work, but it also completely skips the change event.
New Questions: Does the jquery html function have a list of illegal characters that would cause it to fail? Why is it not even registering the change function when it doesn't like the contents of my php include file?
First thing that you must understand is that php runs on the server, all the output is rendered and sent as html code to the browser, and is not available there.
That said, you have at least 2 options :
1.- echo all form options, each one inside a div, that you can hide/show based on the selected choice.
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
<!-- ECHOING ALL FORM OPTIONS -->
<div class="option-form" id="form-option-symbol"><?php include("html/form_number.html"); ?></div>
<div class="option-form" id="form-option-letter"><?php include("html/form_letter.html"); ?></div>
<div class="option-form" id="form-option-other"><?php include("html/form_other.html"); ?></div>
</div>
<style>
div.option-form {
display:none; /* HIDE ALL DIVS BY DEFAULT */
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
// HIDE ALL DIVS
$('div.option-form').hide();
var val = $(this).val();
if (val == "number" || val == "symbol") {
$('form-option-symbol').show();
} else if (val == "letter") {
$('form-option-letter').show();
} else {
$('form-option-other').show();
}
});
});
</script>
2.- Using a template system or load partial html pieces with ajax.
PHP Is a pre-processor so adding later into the website is useless. Just create your form with either setting its html or by using .prepend() or .append() with your form elements.
<form class="myform">
</form>
and in jquery
$('.myform').html('<input type="submit">');
or
$('.myform').append('<input type="submit"');
EDIT :
Read your code wrong looked up
<?php include('test.html'); ?>
don't think that would work.
Instead of
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
and such, try
$("#addhtml").html("<?php include("html/form_number.html"); ?>");
so that the html will be treated as a string.
Also make sure the form files don't have tags such as html, head, and body, and only contain the actual form.
EDIT: I just saw that #nnnnnn already stated this, gotta give credit where credit is due
I think you might just need to change your variable "val" declaration to get your code to work.
I don't think
var val = $(this).val();
will work. Based on the comparison you are making, I believe it should be:
var val = $(this).children("option:selected").text();
which will allow you to get the text value of the select element's selected option.

Add new item in a select tag and refresh it without refreshing the whole page using jquery

How can I refresh a select tag after adding new item into it using Jquery.
HTML :
<select id="exam_select" class="exam_select" name="exam_select" value="Select Exam">
<option value="">Select Exam</option>
<?php
while($row=mysql_fetch_assoc($exam)):
?>
<option value="<?php echo $row['e_code'];?>"><?php echo $row['e_code'];?></option>
<?php
endwhile;
?>
</select>
<input type="text" id="add_new_deg_field" class="hide_show" placeholder="New Exam Name"/>
<button id="add_edu_deg" class="hide_show">Add</button> <p id="save_exam" class="hide_show p_hide_show"></p>
JQuery :
$.ajax({
type:'post',
url:'exam_entry.php',
data: 'add_new_deg_field='+ $('#add_new_deg_field').val(),
success: function(reply_data){
$('#save_exam').html(reply_data);
}
});
return false;
}
By this code I can save new item in my database table by clicking 'add_edu_deg' button. But can't refresh the select tag options. How can I do it using jquery. I search a lot but can't find any solution. Plz help. Thank you.
I am assuming that you want to remove the selected <option> once it has been selected since you haven't defined what you mean by refresh
If that is the case , within the success callback you can do:
$('#exam_select option:selected').remove();
If this is not your intent, the question is not clear enough
You can add an option to a select input with append.
<select><option>Option 1</option></select>
<button>Add option</button>
var x = 2;
$("button").click(function(){
$("select").append("<option>Option "+x+"</option>");
x++;
});
If you somehow save your option to x with ajax (I don't know how, never used ajax before), then execute append on your select, it will be added to the list without needing to be refreshed.
Here is a fiddle of it.
http://jsfiddle.net/8ka5Y/
$('#addOption').on('click',addOption);
var i = 0;
function addOption(){
$('#mooSelect')
.append($("<option></option>")
.attr("value",i++)
.text("Option " + i));
}
which is pretty much what is in the question
What is the best way to add options to a select from an array with jQuery?

Categories