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);
});
});
Related
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.
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 ?
HTML code is :
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
Js Code :
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
and Php Code is :
$option = $_POST['get_option'];
$data = array();
$prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
while ($tqty = $prdqty->fetch_assoc())
{
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
}
echo json_encode($data);
while we selecting first selectbox content, need to add some data to second select box from database, we almost done the things but the second select box didn't show any values ,please help us to resolve the above problem
I tried your code with some hard code value and it perfectly working fine:-
Html+Jquery (in single page with .html extension):-
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
</script>
Php (with hard-coded value):-
<?php
$option = $_POST['get_option'];
$data = array();
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);
Output:-
http://prntscr.com/auyn7i
http://prntscr.com/auymzf
http://prntscr.com/auynij
Note:- problem may be occuring because either you missed jquery library of concatenation inside loop or some other error in your php file.
You need to do two things:
1) concatenate results in while loop. You are re-assigning the array variable causing latest one to overwrite the old one.
This way, only old value will be appended.
Change
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
To
$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
2) Change
$('#freeitem').html(response.fritm);
To
$('#freeitem').append(response.fritm);
As you are just appending options to drop down, not changing its HTML.
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 research in google and stack overflow for this answer there are lot of answer but i cannot able to get what i want.
I have two drop down menus and three text boxes.
PHP Code :
<select onchange="FirstDropDownClick()"> </select>
script code :
<script type="text/javascript">
function FirstDropDownClick() {
var selectDwn = document.getElementById("ID_dwn");
var selectedValue = selectDwn.options[selectBox.selectedIndex].value;
}
In "FirstDropDownClick()" i want the codes for the following :
1.select data from database according to the selected value.
2.Fill the text boxes with that.
3.Fill second drop down according to value of first drop-down menu.
I need an example codes. Because am stuck , dont know how to do .
Thanks in Advance.
your html code
<select name="reg_number" id="reg_number">
<option value="1">Reg1</option>
<option value="2">Reg2</option>
<option value="3">Reg3</option>
</select>
<input type="text" name="first_name" id="first_name">
your jquery(make sure you include jquery file)
$(document).ready(function(){
$('#reg_number').change(function(){
var reg_number = $(this).val();
var data_String;
data_String = 'reg_number='+reg_number;
$.post('ajax_file.php',data_String,function(data){
var data= jQuery.parseJSON(data);
$('#first_name').val(data.first_name)
});
});
});
your php code (ajax_file.php)
<?php
$reg_number =$_POST['reg_number'];
//run your query here to fetch the result and store it in a variable $data
echo json_encode($data);
exit();`
?>
If you want to do it with ajax and php
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
JQuery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$.ajax({
method: 'POST',
url: "test.php",
data: {
'number_value' : number_value
},
dataType:'json',
success: callback = function(data, textStatus, xhr)
{
$('#number_value').val(data.number_value);
}
});
});
});
php (test.php)
<?php
echo json_encode($_POST);
?>
why you need php for that you can do it only with jquery or javascript
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
Jquery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$('#number_value').val(number_value);
});
});