The result of dropdownlist is did not match what I wanted the data that has been selected. I would like to know how to pass the jquery or javascript variable to php or that is another to way to match the dropdownlist data?
function editbtn(id){
$('#employee_id_edit').val(id);
var invoice_id = $('#user-user-list').find("#row_"+id).find("td:eq(1)").text();
var payment_id = $('#user-user-list').find("#row_"+id).find("td:eq(2)").text();
var category = $('#user-user-list').find("#row_"+id).find("td:eq(3)").text();
var sale_person = $('#user-user-list').find("#row_"+id).find("td:eq(4)").text();
var amount = $('#user-user-list').find("#row_"+id).find("td:eq(5)").text();
$('#invoice_id_edit').val(invoice_id);
$('#payment_id_edit').val(payment_id);
$('#product_type_edit').val(category);
$('#employee_edit').val(sale_person);
$('#amount_edit').val(amount);
}
<label for="employee">Sale Person</label>
<select id="employee_edit" name="employee_edit" class="form-control" autocomplete="off">
<?php
$employee_model = $registry->get('loader')->model('user');
$employee = $employee_model->getEmployee();
if(null !== $employee) {
foreach ($employee as $employee) {
?>
<option value="<?php echo $employee['username'];?>" selected><?php echo $employee['username']; ?></option>
<?php
}
} else {
?>
<option>No Employee Available</option>
<?php
}
?>
</select>
I think you should use jquery plugins like 'jquery select2'(https://select2.org/) or create some custom ajax request to send data from js to PHP backend and then get and handle a response from js part.
Related
I'm trying to create a dynamic funktion in jQuery, which handles onchange event for a select (dropdown) and updates to other text fields with some calculated values.
But I'm having some trouble with.
My select is like this
<select name="r514b" id="r514b" size="1" class="listform" style="width: 155px;"> <option value="0">Vælg overfladebehandling</option> <?php while($farverow = mysql_fetch_array($farvequery, MYSQL_ASSOC)) { if ($res['r514b'] == $farverow['id']) {
$r514bselected = "selected";
} else {
$r514bselected = "";
}?> <option value="<?php echo $farverow['id']; ?>" <?php echo $r514bselected; ?> data-nypris="<?php echo $farverow['pris']; ?>" data-grundpris="<?php echo $farvegrundrow['pris']; ?>" data-sumvaegt="<?php echo $res['r477']; ?>" data-db="<?php echo $res['r502']; ?>"><?php echo $farverow['navn']; ?></option> <?php } ?> </select>
and the jQuery is like:
$('#r514b').change(function(){
var ny_pris = $(this).find(':selected').data('nypris');
var grundpris = $(this).find(':selected').data('grundpris');
var sumVaegt = $(this).find(':selected').data('sumvaegt');
var db = $(this).find(':selected').data('db')
var overflade_forskel = ny_pris - grundpris;
// alert(ny_pris);
// alert(grundpris);
// alert(sumVaegt); // * overflade_forskel);
var pris_forskel = (sumVaegt * overflade_forskel)/(1-(ds.r502.value/100));
// alert(pris_forskel);
ds.id514d.value = Math.round(pris_forskel);
ds.r514d.value = Math.round(pris_forskel);
});
The reason I want to make it dynamical is that I need to have multiple selects, which basically does the same thing. Only difference is which text fields they update.
So I was hoping that I somehow to make the function catch the selects dynamic, and update the fields dynamic maybe from some extra data attributes on the selects.
But how do I do that?
I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.
Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>
I have a problem putting Onchange() on a ajax returned html on my form.
Basically I have clients listed in a select.
<select name="company" id="company">
<?php
$sqlget1 = "SELECT * FROM clients WHERE 1=1 ORDER BY company ASC;";
$resget1 = mysql_query($sqlget1);
while($row1 = mysql_fetch_array($resget1)) {
?>
<option value="<?php echo $row1['id']; ?>"><?php echo $row1['company']; ?></option>
<?php
}
?>
</select>
And when some one selects a client, im using Ajax to fetch projects that are assigned to that client.
$('#company').change(function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
It gets returned back to
<div id="response"></div>
The code for get_projects.php is
<?php
include('inc.php');
if(isset($_POST["projects"])) {
$projects = $_POST["projects"];
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
echo '<select name="project" id="project" class="select2 form-control">';
echo '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2)) {
?>
<option value="<?php echo $row2['id']; ?>" pstatus="<?php echo $row2['pstatus']; ?>" ptype="<?php echo $row2['ptype']; ?>"><?php echo $row2['pname']; ?></option>
<?php
}
echo '</select>';
}
?>
Now when i use on change function on the returned html from ajax it is not working.
I tried to see the source code and found out that it is not there atall. It only shows the <div id="response"></div>
But i can see the result on the form but cant see the source in the source code.
Hence i thought that's why the Onchange() is not working for <select name="project" id="project" class="select2 form-control"> because it is not showing.
I see, the data which is return from Ajax is object
You should parse it to get the raw content an set into DIV
When you are dynamically adding mark up to the page the javascript doesn't know about the controls you have added through php.
Try finding the newly added control like this:
var select = document.getElementById('project');
Then you should be able to fire your on change method
Not tested, but it should work
<?php
include('inc.php');
if(isset($_POST["projects"]))
{
$projects = $_POST["projects"];
$varOut = "";
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
$varOut .= '<select name="project" id="project" class="select2 form-control">';
$varOut.= '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2))
{
$varOut.= "<option value=" . $row2['id'] . " pstatus=". $row2['pstatus']. ">ptype=".$row2['ptype']."><".$row2['pname']."></option>";
}
$varOut.= '</select>';
}
echo $varOut;
?>
I've finally solved the issue.
Basicall i just pasted the Onclick() script for '#projects' inside the get_projects.php file.
So now every time when it comes from ajax it also brings the javascript as well.
When you use ajax, you add a piece of html later to the DOM (browsers view), because you use .change the onchange is only added to the '#company' elements wich already exist in the browser.
You need to bind the onchange after you appended the html. for example:
$('#company').change(function() {
onCompanyChange()
});
function onCompanyChange(){
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
$('#company').change(function() {
onCompanyChange()
});
});
}
OR
You can also use an on change, on change does work with elements added later to to the dom. so this code works with elements wich already exists and new added elements with for example ajax
$("#company").on("change",function(){
console.log("change");
});
Try below code. Hope this works fine.
$(document).ready(function() {
$(document).on('change', '#company', function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
});
I am showing the dropdowns based on the above selected dropdowns. I want the result in third dropdown. For that I am writing the sql query in php and writing the change event in jquery but i am unable to get the result. I am stuck up there
My jquery looks like
$(document).ready(function(){
$("#parent_cat,#city").change(function(){
$.get('loadlocation.php?city=' + $(this).val() , function(data) {
$("#sub_cat").html(data);
});
});
});
parent_cat and city are from selected values
<label for="category">Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label for="city">city</label>
<select name="city" id="city">
<?php while($row = mysql_fetch_array($query_parent1)): ?>
<option value="<?php echo $row['city']; ?>"><?php echo $row['city']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
And my php file loadlocation.php is
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$city = $_GET['city'];
$query = mysql_query("SELECT table_place_detail.post_title FROM table_terms, table_place_detail, table_post_locations
WHERE table_place_detail.post_location_id = table_post_locations.location_id AND table_place_detail.default_category = table_terms.term_id AND table_post_locations.city = '$city' AND table_terms.name = '$parent_cat'");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[post_title]'>$row[post_title]</option>";
}
?>
I want to fetch the values of parent_cat, city to loadlocation.php but i am not able to get those values. I want to load the two values and get the query excecuted and the values should shown in 3rd dropdown as below can any one help this issue
<label>Vendors List 1</label>
<select name="sub_cat" id="sub_cat"></select>
Two things stand out
You send only one value, ?city=
According to the manual jQuery.get(), you can send additional parameters as a plain object. This means, you don't need to build a query string, but can pass parent_cat and city separately, e.g.
$.get("loadlocation.php",
{ parent_cat: $('#parent_cat').val(), city: $('#city').val() },
function(data) {
$('#sub_cat').html(data);
});
And finally, the mandatory hint at each mysql_* page
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
I needed make a dinamic dependent dropdown in a form,so i found this solution that uses the JS auto-submit function:
function autoSubmit()
{
var formObject = document.forms['dados'];
formObject.submit();
}
then I use the onchange event in the first dropdown to call the auto-submit function:
<label>Campus:</label>
<select name="campus" onchange="autoSubmit();">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
with this the element "campus" will be setted to be used in the second dropdown SELECT statement:
$campus = $_POST['campus'];
...
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso">
<option VALUE="null"></option>
<?php
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
</select>
this code is working,but the problem is that in this way I cant set a action atribute in the form because if i do this every time the first dropdown changes it will redirect to the action's URL.this is the form that works:
<form name="dados" method="POST" onsubmit="return validar();">
with no action atribute I cant use a submit button to send the data of all the others elements to the right URL.there is a way to this?
You should use Ajax code to populate the second dropdown values.
On Form's page:
<label>Campus:</label>
<select name="campus" id="campus">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso" id="curso">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#campus').change(function(){
var campusName = $(this).val();
$('#curso').load('generateCurso.php?campus='+campusName);
});
});
</script>
Write a PHP file, called generateCurso.php
<?php
$campus = $_GET['campus'];
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
?>
<option VALUE="null"></option>
<?php
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
I solved this issue using a ajax script triggered by "on change" event.the ajax script call a external file that return an array of elements.the script use these elements to populate the dropdown list.