how manage auto-submit with the action atribute in the form - javascript

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.

Related

How to match the variable of JQuery to PHP dropdownlist

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.

How to display data with radio buttons based on drop down selection?

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).']';
?>

Create two dropdown boxes from a multidimensional array in php, one for the key, another one for the item in the key

I have a multidimensional php array as following:
$country = array ("India" => array("Maharashtra","Tamil Nadu","West Bengal"),
"USA"=> array ("New York", "California", "Florida"),
"Canada"=>array("Ontario", "Alberta", "Manitoba"));
I want to create two drop down boxes. One will have the country name. The other will have the state name, which will get populated when the first box is selected.
I have written the code for the first box:
echo "<select name='name'>\n";
foreach($country as $key => $item) {
echo "\t<option>$key</option>\n";
}
echo "</select>\n";
Can anyone suggest me how to create the next drop down box?
Take a look at this sample code. From my understanding you don't want to make use of a database or an additional ajax call so I populated a javascriopt cache variable object with all states
<?php
$data = array("India" => array("Maharashtra", "Tamil Nadu", "West Bengal"),
"USA" => array("New York", "California"),
"Canada" => array("Ontario", "Alberta", "Manitoba"));
$countries = array_keys($data);
?>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>-->
<script>
//Store country as a javascript object
var countries = <?php echo json_encode($data); ?>;
$(document).ready(function () {
$('select[name="countries"]').change(function () {
var country_val = $(this).val();
if (countries[country_val]) {
var options = '<option value = "">Select State</option>';
for (i in countries[country_val]) {
var state = countries[country_val][i];
options += '<option value = "' + state + '">' + state + '</option>';
}
$('select[name="states"]').html(options);
}
});
});
</script>
<!--First Dropdown-->
<div class="country">
<select name="countries">
<?php foreach ($countries as $country): ?>
<option value="<?php echo $country; ?>"><?php echo $country ?></option>
<?php endforeach; ?>
</select>
</div>
<!--Second Dropdown-->
<div class="states">
<select name="states">
<option>Select State</option>
</select>
</div>
It will work. Follow step by step.
YourPage.php
<?
$country = array ("India" => array("Maharashtra","Tamil Nadu","West Bengal"),
"USA"=> array ("New York", "California"),
"Canada"=>array("Ontario", "Alberta", "Manitoba"));
?>
<div class='country'>
<select name="country_name" class="Country">
<?
foreach($country as $countryName => $states) {?>
<option value="<? echo $countryName;?>"><?echo $countryName?></option>
<?}?>
</select>
</div>
<div class="State">
<select>
<option>Select Country</option>
</select>
</div>
Add this code in your .js file.
<script>
$('.Country').change(function(){
var StateName= $('.Country').val();
$.ajax({url:"AjaxSelectState.php?CountryName="+CountryName,cache:false,success:function(result){
$('.State').html(result);
}});
});
</script>
AjaxSelectState.php
(Create this page. And, make sure if you want to change name of this page, change in <script></script> tag too. Both are related)
<?
$CountryName=$_GET['CountryName'];
$totalState=sizeof($country[$CountryName]);
?>
<select name="states_<?echo $CountryName;?>">
<?
for($i=0;$i<$totalState;$i++)
{?>
<option value="<?echo $country[$CountryName][$i];?>"><?echo $country[$CountryName][$i];?></option>
<?}?>
</select>
Try this:
// Build country array
$country = array ("India" => array("Maharashtra","Tamil Nadu","West Bengal"),
"USA"=> array ("New York", "California", "Florida"),
"Canada"=>array("Ontario", "Alberta", "Manitoba"));
// Output the country selection
echo '<select name="country_name" id="country_select">';
foreach($country as $countryName => $states) {
echo '<option value="'.$countryName.'">'.$countryName.'</option>';
}
echo '</select>';
// Output a select for the state selection per country
foreach($country as $countryName => $states) {
echo '<select class="state_dropdown" name="states_'.$countryName.'" style="display: none;">';
foreach($states as $state){
echo '<option value="'.$state.'">'.$state.'</option>';
}
echo '</select>';
}
Please note that this will actually create 4 selects. This is because depending on the selection for the first < select >, you should show the appropriate second < select >
Example Javascript:
This JS requires jQuery be loaded on your page before this code is run.
// When the document has loaded...
jQuery(document).ready(function(){
// Find the country select and listen for a change...
jQuery('#country_select').change(function(){
// When this change happens, hide all state fields
jQuery('.state_dropdown').hide();
// Get the country the user selected
var country = jQuery(this).val();
// And show only the state field they need to see.
jQuery('select[name=states_'+country+']').show();
});
});

Onchange form filter with dropdown

I am trying to create a filter for a gallery that I've created. The gallery has 5 filters using dropdown menu's. When a item is selected from one of the 5 filters it has to filter the images. When a second filter is selected it has to filter the results of the first filter and so on.
I am using the onchange='this.form.submit()' script but I don't know how to assign a certain action to it when an item is selected. This is my code at the moment of writing:
<td>
Kleur:
<form method="POST">
<select name="kleur" onchange='this.form.submit()'>
<option> -- Geen optie -- </option>
<?php while ($line1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $line1['kleur']; ?>"> <?php echo $line1['kleur']; ?>
</option>
<?php } ?>
</select>
</form>
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
</br>
</td>
The following part doesn't seem to work:
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
Does anyone know how to use this script? and perhaps explain how to save the selected item in the dropdown menu too?
You can add an attribute with all the information you need to filter to your images
<img filterInfo="Kleur|Geur|Bloemvorm|Gezondheid|Type|Zoeken">
then set a class for all your filters to catch the changes
$(".filters").on("change",function(){
var kleur = $('[name=Kleur]').val();
var Geur = $('[name=Geur]').val();
...
...
...
$.each($('#gallery img'),function(i,v){
var attrs = $(v).attr("filterInfo").slice("|");
if((kleur == "" || kleur == attrs[0]) && (Geur == "" || == attrs[1]) .... other filters)
$(this).show(); //or fadeIn();
else
$(this).hide(); //or fadeOut();
});
});

get the result for third dropdown by passing the selected dropdown values

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()

Categories

Resources