Run script if selected value is changed - javascript

I want to run a PHP script if the value is changed in my dropdown. The PHP script should run an if else statement. Is it possible to run this script, without a form POST?
Here is my dropdown:
<select id="data" name="data" class="select2_single form-control">
<option value="1">Data 1</option>
<option value="2">Data 2</option>
</select>
Here is the script I want to execute:
<?php
if($_POST['data'] != '1') {
echo 'Value 1 is selected';
}
if($_POST['data'] != '2') {
echo 'Value 1 is selected';
} else {
echo 'No value selected';
}
?>

Also you can do this using just plain JavaScript:
var dataEl = document.querySelector('#data'),
outputEl = document.querySelector('#output');
dataEl.onchange = function() {
outputEl.innerText = dataEl.value
? 'Value ' + dataEl.value + ' is selected'
: 'No value selected';
};
<select id="data" name="data" class="select2_single form-control">
<option value="">Select...</option>
<option value="1">Data 1</option>
<option value="2">Data 2</option>
</select>
<p id="output"></p>

Try this js code for change value and handle post data at php end:
$(document).ready(function() {
$("#data").change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
data: 'id='+ id,
url : "dynamic_select.php",
success: function(data) {
//Handle returned data
}
});
});
});

Related

How can I get a dependent dropdown selected value?

I am new at development, right now I am learning laravel 9 and I am trying to get a dependent dropdown selected value. Here is my blade file:
<div class="form-group">
<label for="vendor_state">State</label>
<select class="form-control" style="color: #000;" id="vendor_state" name="vendor_state">
<option selected disabled>Select State</option> #foreach ($states as $state)
<option value="{{ $state->id }}" #if(!empty($state->id==$vendorDetails['state'])) selected #endif>{{ $state->name }}</option> #endforeach
</select>
</div>
<div class="form-group">
<label for="vendor_city">City</label>
<select class="form-control" style="color: #000;" id="vendor_city" name="vendor_city"></select>
</div>
And here is the script:
<script type="text/javascript">
$(document).ready(function () {
$('#vendor_state').on('change', function () {
var stateId = this.value;
$('#vendor_city').html('');
$.ajax({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{ route('cities') }}?state_id='+stateId,
type: 'get',
success: function (res) {
var dropdown = $('#vendor_city');
dropdown.html('<option selected disabled value="">Select City</option>');
$.each(res, function (key, value) {
dropdown.append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
});
});
</script>
For now, I can save the values of the state and the city in the database and get the selected value of the state. How can I get the selected value of the city?
I tried storing the selected value in dropdown var and display it using if condition inside the option value of the script.
Some time ago, I wrote a similar script for another system. Chose country, then a dropdown with Regions(states) list appears. Upon Choosing a region, a list of Departments (Cities) appears.
Note:
In the database, I have relations from Regions (states) to Countries and from Departments to regions. I.e.:
In the Regions database table, I have a field named "country_id", and in the Departments table I have a column "region_id"
My code was as follows:
The main page with the dropdowns
//Country drop-down select
<select style="max-width:150px;" name="country_id" id="country-list" onChange="getRegion(this.value);">
//Options with list of countries names and ID in foreach loop
<option value="' . $country->id . '">' . $country->name . '</option>
</select>
<select name="region_id" id="region-list" onChange="getDepartment(this.value);">
<option value=""><?= $langs->trans('SelectRegion') ?></option>
</select>
<select name="department_id" id="department-list" class="demoInputBox">
<option value=""><?= $langs->trans('SelectDepartment') ?></option>
</select>
The AJAx function:
function getRegion(val) {
$.ajax({
type: "POST",
url: "region.inc.php",
data: 'country_id=' + val,
success: function (data) {
$("#region-list").html(data);
}
});
}
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
function getDepartment(val) {
$.ajax({
type: "POST",
url: "department.inc.php",
data: 'region_id=' + val,
success: function (data) {
$("#department-list").html(data);
}
});
}
function selectRegion(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
"region.inc.php" is:
$country_id = $_POST['country_id'];
<option value=""><?= $langs->trans('SelectRegion') ?></option>
$regions_array = function_to_get_regions_ids_and_names_in_array
foreach ($regions_array as $result) {
print '<option value="' . $result->region_id . '">' . $result->department_id . '</option>';
}
"departments.inc.php"
$region_id = $_POST['region_id'];
$departments_array = function_to_get_departments_ids_and_names_in_array
<option value=""><?= $langs->trans('SelectDepartment') ?></option>
foreach ($departments_array as $result) {
print '<option value="' . $result->department_id . '">' . $result->department_name . '</option>';
}

keep old select value while validation failed in ajax in laravel

In my Laravel project I have an appointment form where patient can choose a doctor after choosing a branch from the dropdown list. I use AJAX for doing the functionality.
Now after any validation failed all the form value restored accept the doctor.
But I want to automatically restored that selected doctor after validation failed.
html form
<select class="form-control appointment_form_searchField" id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
<option value="">Select Branch</option>
#if($_SESSION['branch'] != null)
#foreach($_SESSION['branch'] as $data)
<option value="{{ $data->id }}">{{ $data->name }}</option>
#endforeach
#endif
</select>
<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;">
<option value="">Select Doctor</option>
</select>
AJAX
jQuery(".appointment_form_searchField").change(function() {
var branch_id = $("#appointment_branch").val();
var token = $('input[name=_token]').val();
if(branch_id.trim() != '')
{
jQuery.ajax({
url:"{{ url('/filter_doctor') }}",
type: 'GET',
data: {_token :token, branch_id : branch_id},
success:function(msg){
$('#appointment_doctor option').remove();
trHTML = '';
trHTML += "<option value=''>Select Doctor</option>";
msg.forEach(function(item){
trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
});
$('#appointment_doctor').append(trHTML);
}
});
}
});
controller
public function filter_doctor(Request $request)
{
$branch_id = $request->branch_id;
$query = DB::table('service_doctors');
$query->select('doctor_id','inactive_dates_in_this_month');
if($branch_id != '0')
$query->where('branch_id','=', $branch_id);
$result_time = $query->get();
$array_doctor_id = $result_time->pluck('doctor_id');
$doctor = Doctor::whereIn('id', $array_doctor_id)->get();
return $doctor;
}
Anybody Help please ? Thanks in advance
If you are using Laravel 5 then you can do something like this.
In your form add missing details appointment_branch and appointment_doctor like below.
The Request::old() option load previous posted value in from hence you need to first select old value for appointment_branch'. Also temporary storeold appointment_doctorvalue indata-oldid` so the script can identify which was the old value submitted by user and can load this select box when document is ready.
<select class="form-control appointment_form_searchField" id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
<option value="">Select Branch</option>
#if($_SESSION['branch'] != null)
#foreach($_SESSION['branch'] as $data)
<option value="{{ $data->id }}" {{ Request::old()?(Request::old('appointment_branch')==$data->id?'selected="selected"':''):'' }}>{{ $data->name }}</option>
#endforeach
#endif
</select>
<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;" data-oldid="{{ Request::old()?Request::old('appointment_doctor'):'' }}">
<option value="">Select Doctor</option>
</select>
And then write your script like below.
<script>
jQuery(document).ready(function($){
if(jQuery("#appointment_doctor").data('oldid')!='' && typeof(jQuery("#appointment_doctor").data('oldid'))!="undefined"){
jQuery(".appointment_form_searchField").change();
}
});
jQuery(".appointment_form_searchField").change(function() {
var branch_id = $("#appointment_branch").val();
var token = $('input[name=_token]').val();
if(branch_id.trim() != '')
{
jQuery.ajax({
url:"{{ url('/filter_doctor') }}",
type: 'GET',
data: {_token :token, branch_id : branch_id},
success:function(msg){
$('#appointment_doctor option').remove();
trHTML = '';
trHTML += "<option value=''>Select Doctor</option>";
msg.forEach(function(item){
trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
});
$('#appointment_doctor').append(trHTML);
}
if(jQuery("#appointment_doctor").data('oldid')!='' && typeof(jQuery("#appointment_doctor").data('oldid'))!="undefined"){
jQuery('#appointment_doctor').val(jQuery("#appointment_doctor").data('oldid')); //select the old doctor id here
}
});
}
});
</script>

Laravel - Ajax call not responding

I am trying to Post the data from the dropdown box and sent the request using Ajax. It is working fine on the localhost but its not working properly on the shared-hosting. I have 3 dropboxes and the value changes according to the values selected from its parent dropbox. For Eg: Car Make (Audi) -> Car Model -> (A4, A5, Q5 etc.. audi models) ->year (19XX - 2019)
I am only able to select the Make, but I am not able to get any data from the Car Make selected.
home.blade.php
<div class="form-group">
<select class="form-control dynamic" name="Make" id="Make" data-dependent='Model'>
#foreach($carLists as $carMake)
<option value="{{$carMake->Make}}">{{$carMake->Make}} </option>
#endforeach
</select>
</div>
<div class="form-group">
<select class="form-control dynamic" name="Model" id="Model" data-dependent='Year'>
<option value="">Select Model</option>
</select>
</div>
<div class="form-group">
<select class="form-control dynamic" name="Year" id="Year" data-dependent='Body'>
<option value="">Select Manufacturing year</option>
</select>
</div>
<script>
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('pagescontroller.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
})
}
});
$('#Make').change(function(){
$('#Model').val('');
$('#Year').val('');
$('#Make').val($(this).val());
console.log($('#HidMake'));
});
$('#Model').change(function(){
$('#Year').val('');
});
});
</script>
PageController.php
class PagesController extends Controller
{
function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = DB::table('carLists')
->where($select, $value)
->groupBy($dependent)
->get();
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
Routes (web.php)
Route::post('inc/sidebar/fetch', 'PagesController#fetch')->name('pagescontroller.fetch');
I am being trying alot but no clue whats going wrong here, however, on the localhost its working fine.
thanks for the time.
Try changing the url to
var url = APP_URL + '/inc/sidebar/fetch';
and set header
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
instead of
var _token = $('input[name="_token"]').val();
and let me know, the result you are getting for this.

select box using ajax and CakePHP

I'm trying to get data related to parent data from select options , and here's my add.ctp
<select name="id" id="category">
<option value="hide">-- اختر مجموعة الصنف --</option>
<?php foreach ($warehouseCategoriesItems as $warehouseCategoriesItem): ?>
    <option value="<?php echo $warehouseCategoriesItem; ?> " ><?php echo $warehouseCategoriesItem; ?></option>
<?php endforeach; ?>
</select>
<select name="id" id="item">
<option>-- اختر الصنف-- </option>
</select>
and here's the script for that :
<script type="text/javascript">
var types_list = $('#item');
$('#category').change(function(){
carId = $(this).val();
$.ajax({
type: "GET",
url: '../warehouse-add-orders-items-form7/add/' + carId ,
data: { 'carId': carId },
success: function( response ) {
types_list.empty();
types_list.append(
$("<option></option>")
.text('-- إختر نوع --')
.val('')
);
$.each(response, function(id, name) {
types_list.append(
$("<option></option>")
.text(response[id].category_item_name)
.val(response[id].warehouse_categories_items_id)
);
});
types_list.trigger('chosen:updated');
}
});
});
.There's relationship between the category parent and the child items , but i'm getting the child with null values each time and the parent back with it's value .
can any one tell me the problem here ?

After ajax rerun php

I have an select menu that submits without reloading the page as follows:
<select id="option" name="option">
<option value="15">15/option>
<option value"30">30</option>
<option value"90">90</option>
</select>
It will submit to the current page as follows, without reloading the page
<script type="text/javascript">
$('#option').change(function(){
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];",
data: "option="+option_val,
success: function(data)
{
window.alert(data)
}
});
});
</script>
The result of a change in the option menu is an popup window with all the code of the page echoed back.
What i want to do on the page is use the $_POST['option'] that is submitted and recalculate a price for example
<body>
//some code and div's
<?php
if (isset($_POST['option'])) {
$option = $_POST['option'];
$price= $row_product['price'] + $option;
echo $price;
} ?>
</body>
The are several places where I would like to use the submitted option value
Any help welcome
Sorry if it is very obvious
The only way is making a PHP page that does the calculation
HTML/page1.php
<select id="option" name="option">
<option value="15">15</option>
<option value="30">30</option>
<option value="90">90</option>
</select>
<div id="dynamic">
<p>DEFAULT CONTENT</p>
</div>
HTML/page2.php
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
//do calculations
echo "<my-html-stuff>lorem ipsum</my-html-stuff>";
JS
var dynamic = $("#dynamic");
$('#select').on("change", function() {
var selected = $(this).val();
dynamic.load("page2.php?option=" + selected, function() {
dynamic.html("<p>CONTENT OPTION "+selected+"</p>");
});
});
Fiddle ==> https://jsfiddle.net/tonysamperi/4dbwwn3g/
WITH JSON
page2.php
header('Content-Type: application/json');
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
$response = ["result" => $option];
echo json_encode($response);
JS
$('#select').on("change", function() {
var selected = $(this).val();
$.get("page2.php?option=" + selected, function(response) {
//do stuff with data
console.debug("RESPONSE", response);
});
});

Categories