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.
Related
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>';
}
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>
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);
});
});
I am building a form that will have three related drop down menus. First one is store locations, second Equipment at this location, third is components at this location.
So when I pick a location the page sends an AJAX request to load the select values for the equipment at this location. And when I pick the equipment it should load the components that belong to that equipment.
The third drop down for components is what's not appearing.
So my first drop down goes like this off the main file with the divs where the drop downs are added via AJAX calls:
<div class="input-group">
<strong>Select A Store Location:</strong>
<select class="form-control selectDesk" name="Location_ID" id="Location_ID">
<option value=1>HT1</option>
<option value=2>HT2</option>
<option value=3>HT3</option>
<option value=4>HT4</option>
<option value=5>HT5</option>
<option value=6>HT6</option>
</select>
</div>
<div id="equipment">
</div>
<div id="component">
</div>
The second drop down is dynamic loaded off a different file and inserted in a div via Jquery and AJAX. This is the code to make that happen
<?php
include('DBConnect.php');
$locID = $_POST['loc_id'];
$equipSQL ="SELECT Equipment_ID, Equipment_Name FROM Equipment WHERE Location_ID = $locID";
$equipResult = $my_dbhandle->query($equipSQL);
$numResults = $equipResult->num_rows;
?>
<strong>Select Equipment:</strong>
<div class="input-group">
<select class="form-control" name="Equipment_ID" id="Equipment_ID" style="min-width: 375px;">
<option value="0">No Equipment Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $equipResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Equipment_ID'] . ">" . $row['Equipment_Name'] . "</option>\n";
}
?>
</select>
</div>
And my third drop down is also loaded off another file via Jquery and AJAX
<?php
include('DBConnect.php');
$equipID = $_POST['equip_id'];
$compSQL ="SELECT Component_ID, Component_Name FROM Components WHERE Equipment_ID = $equipID";
$compResult = $my_dbhandle->query($compSQL);
$numResults = $compResult->num_rows;
?>
<strong>Select Component:</strong>
<div class="input-group">
<select class="form-control" name="Component_ID" id="Component_ID" style="min-width: 375px;">
<option value="0">No Component Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $compResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Component_ID'] . ">" . $row['Component_Name'] . "</option>\n";
}
?>
</select>
</div>
The Jquery is as follows:
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
}
});
}).change();
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
</script>
So again, the first AJAX request for the second equipment drop down is loaded just fine. But the third drop down for the component select is not.
Thank you in advance for your help!
Hi I have modified your code please use this.
If this will work then I will explain the script
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
initSecond();
}
});
}).change();
function initSecond(){
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
}
</script>
Try to execute this javascript :
$("#Equipment_ID").change(function(){ ....
... after the first ajax call, like this:
success: function (r) {
$('#equipment').html(r);
$("#Equipment_ID").change(function(){
...
...
}
}
Also the third dropdown should be:
<select name="Component_ID" and id="Component_ID" ...
I'm working on a form. There are select elements and their options are from a database.
When i choose the first (for example a school class) the second have to show only those names who are in the class selected at first, from database too.
I'm rookie at Javascript and JQuery so I'm okay with page refreshing PHP solutions but I can't figure it out on my own. Can you please give me some instructions or advices how to start to work on this?
You can achieve this with ajax using preferably jquery and json.
javascript/ajax:
function fillSecondSelect()
{
$.get("ajaxFill.php?id=" + $("#class").val(),"",function(data) {
var selectData = "<option value=''> - Choose Student - </option>";
data = JSON.parse(data);
for(i=0;i<data.length;i++)
{
selectData += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#students").html(selectData);
});
}
html:
<select id="class" name="class" onchange="fillSecondSelect()">
<option value=""> - Choose Class - </option>
<option value='1'>Class A</option>
<option value='2'>Class B</option>
</select>
<select id="students" name="students"></select>
ajaxFill.php (which should get the student data according the class id sent from mysql and serve it as JSON):
$result = mysqli_query($link,"SELECT * FROM students WHERE class_id = '" . $_GET['id'] . "'") or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result))
{
$students[] = array("id" => $row['student_id'], "name" => $row['student_name']);
}
echo json_encode($students);
You use Jquery and Ajax to fetch the Students in a class based on the Class selected and load the student list into a Select element without refreshing the page.
HTML
<select id="selectedclass" onBlur="loadstudent();">
<option>class 1</option>
<option>class 2</option>
<option>class 1</option>
</select>
<select id="students" ></select>
Javascript
function loadstudent(){
var selectedclass = $('selectedclass').val();//user id
$.ajax({
type:'POST',
url: your php script,
data: 'selectedclass='+selectedclass,
dataType: 'json',
success: function(data)
{
var classlist='', html;
for(var i = 0; i < data.length; i++) {
classlist = data[i];
html+=classlist.students
}
//get number of outbox
$('#students').html(html);
},
error: function(jqXHR, exception) {
alert('Error');
}
});
}
PHP
<?php
include "config.php";//database connection file
//database using PDO
$db = pdoDB::getConnection();
//data from html
$student_class=$_POST['selectedclass'];
$query = "SELECT student_lastName,student_firstName
FROM student_table WHERE student_class='student_class'";
$result = $dbase->query($query) or die("failed!");
while ($row = $result->fetch(PDO::FETCH_BOTH)){
//credits info
$studentlist="<option>".$row['student_lastName']." ".$row['student_firstName']."</option>";
$results[] = array("students"=>$studentlist);
}
header('Content-type:application/json');
exit (json_encode($results));
?>
The data sent from the PHP script should be encoded with JSON
Modern websites use ajax to do this.
After the first item is selected an ajax request is sent which delivers the data for the second select.
There are many ways to build the second select. The ajax response could contain a json array with all the data and then you build the select field with js.
Or the response delivers complete html and all you have to do is to insert it.
I think this is exactly that you mean: http://codepen.io/man/pen/oBFlE
Put the js code in your file. You can have as many levels as you want. Explaining:
<select name="level1"><!--this is the "main" select-->
<option value="level2A">Level2A</option>
<option value="level2A">Level2B</option>
</select>
<select name="level2A"><!--this shows when the user selects the option with name ""level2A"-->
<option value="level3"></option>
</select>
<select name="level2B">
<!--options...-->
</select>
<select name="level3"></select>