Select on change/submit inside Ajax - javascript

I have a form that gets submitted via ajax, inside that form there are two selects. these two selects get data from mysql using php.
I want is to show the second select only when the first select has been chosen, I've tried onchange and onsubmit but didn't get it to work. ajax script keeps preventing that! i even tried passing the value of the first select vie js to php, didn't work too.
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<?php
$s1= "<script>document.writeln(recMarque());</script>";
echo $s1;
?>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
<?php
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
</select>
Static html:
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<script>document.writeln(recMarque());</script>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
I appreciate your help

Why are you using inline javascript while you are already loading the huge file of jQuery? Use jQuery change event and wrapp your hole code inside a jQuery DOM ready event. Additionnaly why are you mixing PHP with markup and javascript, this goes in contradition of AJAX purposes and of your goal descrption. You want to show the second select after selection from first select and the content depends on selected value (which require server side fetching) then send an XMLHTTPRequest to a separate (small) file and get the response.
$('select[name=sel1]').change(function(e) {
e.preventDefault();
var value = $('select[name=sel1] option:selected').val();
var text = $('select[name=sel1]',this).text();
var urlForSelect2 = $('select').attr('data-url');
// make an AJAX call and send value, text, and all your needed variable alongside
$.ajax({
type: "GET",
url: urlForSelect2,
dataType: 'html',
data: ({value: value, text: text}),
success: function(data){
$('select[name=sel1]').append(data);
});
return false;
});
And seperate the the php responsible for creating into another file with another url (urlForSelect2 in this case):
<option value="" hidden selected>Choose</option>
<?php
// Get the values sent along AJAX request using PHP $_GET, let's say $s1
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
And the markup is becoming smaller and readable like:
<select class="form-control" name="sel1" data-url="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>

Here is my solution
In the first select i've put onchange="selChange", the function is as follows:
<script type="text/javascript">
function selChange(){
var val = $("#sel1").serialize();
$.ajax({
type: "POST",
url: "select.php",
data: val,
success: function(data) {
$('#sel2').html(data);
}
});
return false;
}
</script>

Related

Change content based on a drop down selection from a mysql database

I have a form of drop down boxes populated with values from a mysql database (Computer Part Models). My goal is to produce the rest of the values (The part's specs) from the database below each drop down box based on the value that was selected.
Essentially what I think I think I need is some sort of div refresh for each time a new item has been selected.
I have tried different functions triggered by 'onchange' within the select tag but nothing has come up working.
Let me know if anymore code would be needed for context.
HTML & PHP for one drop down
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<?php
$cresult = $mysqli->query("SELECT * FROM pCpu ORDER BY cModel asc");
?>
<select id="CPU" name="CPU">
<option value="" disabled selected>Select your Part</option>
<?php
while ($rows = $cresult->fetch_assoc()) {
$cmodel = $rows['cModel'];
echo "<option value='$cmodel'>$cmodel</option>";
$cid = $rows['ID'];
}
?>
</select>
<br/>
<?php
$res = $mysqli->query("SELECT cSocket FROM pCpu WHERE ID = '$cid'");
while($rows = $res->fetch_assoc()) {
$csocket = $rows['cSocket'];
echo "CPU Socket: $csocket<br/>";
}
?>
<br/><br/>
What would be the best way of tackling this?
Thanks in advance!
There's two parts in this answer :
First if you want to update a part of your page with change event on the select
function myUpdateFunc()
{
var mySelected = $("#CPU").find("option:selected").val();
$('#divResults').html ('selected value :' + mySelected)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<select id="CPU" name="CPU" onchange="myUpdateFunc()">
<option value="" disabled selected>Select your Part</option>
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
<br/>
<div id="divResults"/>
<br/><br/>
Next :
If you want to query a database you can check many tutorials on this. I can help you with this as well

Splice method in codeigniter drop down

I have some locations that are stored in my database separated by a comma and I have a dropdown that gets that information. The user selects a location to populate another drop down based on this chosen location.
Here is my php code:
<label for="select-service">
<strong>Enter a Location:</strong>
</label>
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
?>
<option value="<?php echo $location->notes ?>"><?php echo $location->notes ?></option>
<?php
}
?>
</select>
Here is my javascript code:
$(document).ready(function() {
FrontendBook.initialize(true, GlobalVariables.manageMode);
GeneralFunctions.enableLanguageSelection($('#select-language'));
$('#select-provider').html('');
$('#select-location').change(function() {
$('#select-provider').html('');
var selected_location = $(this).val();
$.ajax({
url: '<?php echo site_url('appointments/getProviderByLocation'); ?>',
type: 'POST',
data: {
csrfToken: GlobalVariables.csrfToken,
'selected_location': selected_location,
},
dataType: 'json',
success: function(data) {
var options = '';
$.each(data, function(key,val) {
console.log(val.id);
options += '<option value="'+val.id+'">'+val.first_name+" " +val.last_name +'</option>'
});
$('#select-provider').html(options);
}
});
});
and here is a screenshot of the location how it is currently:
So what i want to achieve is to have Randburg as one option, Greenside as another option and Rosebank as another option.
You have different type string in your array so for this particular problem in your loop you should explode your string like this and another loop to print separated string
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
$LocationsArray = explode(",", $location->notes);
foreach($LocationsArray as $singleLocation):
?>
<option value="<?=$singleLocation ?>"><?=$singleLocation ?></option>
<? endforeach;
};?>

how we can use in Laravel Jquery onchange element in select?

<script>
$('#brand_id').on('change',function(e){
console.log(e);
var brand_id = e.target.value;
//ajax
$.get('/product_id?brand_id =' + brand_id, function(data));
//success data
$.each(data, function(upload_form, product_cat){
$('product_category').empty();
$('product_category').append('<option value="'+ product_cat.id +'">'+ product_cat.product_hierarchy +'</option>');
});
});
Above is my Jquery code check this and point out me what is the problem.
<form enctype="multipart/form-data" action="{{action('BrandController#upload_csv')}}" method="post">
Brand Code
<select name="brand_id" id="brand_id" Select="" class="form-control">
<option value="">--Select Brand Code--</option>
<?php foreach ($brands as $row) { ?>
<option value="<?= $row->brand_id ?>"><?= $row->brand_name ?></option>
<?php } ?>
</select>
Product Id
<select name="product_category" id="product_category" Select="" class="form-control">
</select>
Status
<select name="status" Select="" class="form-control">
<option value="">--Select Product Status--</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<input type="hidden" name="_token" value="<?= csrf_token(); ?>">
Upload Valid csv file
<input type="file" name="csv" required class="form-control">
<br/>
<input type="submit" value="Upload" class="btn btn-primary">
</form>
This is my form. in the form there is a select in which onchange element i want to show sub categories in next select. Below is my Route file code.
Route::get('/product_id', function(){
$brand_id = Input::get('brand_id');
$product_id = product_hierarchy::where('bcategory_code','=',1)->get();
return Response::json($product_id);
});
In Laravel 5.2 we have to pass the csrf token to execute the request.
just try like this...
<script>
$('#brand_id').on('change',function(e){
console.log(e);
var brand_id = e.target.value;
//ajax
$.get('/product_id?brand_id =' + brand_id,{"_token":$("input[name='_token']").val()}, function(data));
//success data
$.each(data, function(upload_form, product_cat){
$('product_category').empty();
$('product_category').append('<option value="'+ product_cat.id +'">'+ product_cat.product_hierarchy +'</option>');
});
});
</script>
I just add this line of code to your get request:
{ "_token" : $("input[name='_token']").val() }
Good Luck.. Happy Coding!!!
Edited
For detailed information about this you can found on the below linked tutorials:
Laravel CRUD Using jQuery AJAX PART – 1
Laravel CRUD Using jQuery AJAX PART – 2

Ajax form duplicating on submit

I have 3 selectboxes the value of each selectbox gets populated based on the selection of the selectbox before it:
selectbox1 =>populates => selectBox2 => populates selectBox 3:
Now when user clicks submit I want to use the values from the selectboxes to query my database
My Problem
When I click submit:
The Whole Form Gets Duplicated (see image below)
So in short the variables are being passed correctly to my php code but the form duplicates on submit...
Code for sending form data
I believe the problem is somewhere in this code
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {$('#resultForm').append(data); }
});
}
});
</script>
HTML
<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
include('connect.php');
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
You're appending the result.
If you don't want to duplicate then replace the new content with old one.
Just change this
success: function(data) {$('#resultForm').append(data); }
to
success: function(data) {$('#resultForm').replaceWith(data); }
or even
success: function(data) {$('#resultForm').html(data); }
See more details about replacewith here

Form fields stability when using jquery to create the form

I am using json to fill the options of select tag, when I choose the country, system synchronously fill the combobox of cities
<label class="AddressLable">الدوله</label>
<select name="country" id="countryCB">
<option >اختر</option>
<?php $cntr=0;
while($cntr < count($countries))
{
?>
<option value="<?php echo $countries[$cntr]['countryNo']?>" <?php echo $_POST['country']==$countries[$cntr]['countryNo']?'selected':''?>> <?php echo $countries[$cntr]['countryName'];?></option>
<?php
$cntr++;
}
?>
</select>
<label class="AddressLable">المدينة</label>
<select name="city" id="cityCB">
</select>
//here is the jquery script
$("#countryCB").change(function(){
var countryNo=$(this).val();
var param={"action":"getCities",
"countryNo":countryNo
};
$.getJSON("controllers/Customer.controller.php",param,function(result){
input=$("#cityCB");
$('>option',input).remove();
$("#cityCB").append('<option> اختر</option>');
$.each(result,function(i,val){
var option = $('<option />');
option.attr("value",val.cityNo);
option.text(val.cityName);
$("#cityCB").append(option);
})
});
How can I make something like this:
<?php echo $_POST['country']==$countries[$cntr]['countryNo']?'selected':''?>
in jquery?
$("cityCB option[value='your_value']").attr("selected", true);
Run it after you append all of the options.

Categories