How to call Web Service when selected option HTML? - html

I have two select option HTML: Category, subCategory, and subCategory must be dependence of Category ( A item as Category contains many subCategory).
My code to show Category:
<select id="categoryID">
#foreach($category as $item)
<option id="{{$item->id}}">{{$item->name}}</option>;
#endforeach
</select>
subCategory:
<select id="sub_category">
#foreach($sub_category as $item)
<option>{{$item->name}}</option>;
#endforeach
</select>
I want to when anyone selected a item in Category, it will call Web service like '/change_category', and return new variable $sub_category dependence ID of Category you selected.
Don't think about function return new variable $sub_category, I just want to ask: How to call Web service when selected option? Thanks.

<select id="categoryID" onchange="changeCategory(this)">
#foreach($category as $item)
<option id="{{$item->id}}">{{$item->name}}</option>;
#endforeach
</select>
<script type="text/javascript">
function changeCategory(id){
var category = id[id.selectedIndex].id;
$.ajax({
type: "POST",
url: url,
data: {
id: category
},
success: function (data) {
//push data here
}
});
}
</script>

Related

MVC - dropdown process ajax call on change function

Not sure what I am doing wrong here but the on change function is not hitting for some reason. I hope someone here can point me in the right direction.
I have a view that has some bootstrap tabs, inside one of those tabs I have a dropdown list. What I want to happen is, when the user selects a year, it make an ajax call to controller, gets the json data and populates a table with the data. Here is my code:
In the View:
<div id="StatementsTab" class="tab-pane fade">
<div class="text-left dash-left-padding dash-right-col-content-billing">
<select class="form-control edi-blue" id="ddlStatements">
<option value="0">VIEW STATEMENTS</option>
<option value="#DateTime.Now.Year">#DateTime.Now.Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-1).Year">#DateTime.Now.AddYears(-1).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-2).Year">#DateTime.Now.AddYears(-2).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-3).Year">#DateTime.Now.AddYears(-3).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-4).Year">#DateTime.Now.AddYears(-4).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-5).Year">#DateTime.Now.AddYears(-5).Year STATEMENTS</option>
</select>
<br />
<table id="statementtbl">
<tr>
<td></td>
</tr>
</table>
and the jquery:
$("#ddlStatements").change(function () {
console.log("change function yes");
var yr = $("#ddlStatements").val();
if (yr > 0){
$.ajax({
//var url = '../LabOrder/DeletePatientNoteAttachment?PatientNotes=' + JSON.stringify(yr);
url: '..Members/GetStatements',
data: 'Year=' + yr, // Send value of the drop down change of option
dataType: 'json', // Choosing a JSON datatype
success: function (data) {
console.log("success");
// Variable data contains the data you get from the action method
},
error: function (ex) {
console.log(ex);
}
});
}
});
I am not sure why but the console log is not being hit. Please help...

How to get html select option value with ng-model angular js

I want to show value on select option with ng-model but value doesn't show. This is my update page, so i must need ng-model from which i send my country_id also i need to show country name here is my code
<select data-ng-model="ticket[0].country_id" ng-option="x in ticket['get_country']"id="country">
<option value="{{ x.name }}">{{ x.name }}
</option>
</select>
this is the code from which i get the name of country from angularjs code
.then(
function successCallback(response) {
console.log(response.data['get_country'][0]['name']);
$scope.country = response.data['get_country'][0] ['name']
$scope.ticket = response.data;
},
function errorCallback(response) {
alert("Error. Try Again!");
}
You can use ng-options like this
<select data-ng-model="ticket[0].country_id" ng-option="x.name as x.name for x in ticket['get_country']"id="country"></select>
if you print the model, you can see the name of the item that what you selected.

Complicated AJAX update with two select elements

I have a form with two select elements where users can select a product variant (for example red, green, blue shirt) and the quantity.
When changing the variant/quantity, I do a AJAX request to get the price.
The complicated part is: each variation has its own price and its own quantities. For example red shirts are 10 USD and at a minimum quantity of 5 (10, 15…). Green shirts are 15 USD but quantity starts at 3 (6, 9…).
(Color/shirt just an example, real products are control units for streetlights :-)
The problem is, when the default is 'red' and '5' and I change to 'green' the price shows 75 USD (AJAX query was green+5). But green only has quantities of 3, 6, 9 etc.
I could return the minimum quantity from my AJAX request, but then the user can't update the price when changing the quantity select.
Only solution I see is make two doSubmit() functions and two submitAjax(). But this would mean I have a lot of duplicate code.
HTML
<form action="" id="product_selection">
<select name="product_variation">
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<select name="product_quantity">
<option value="">10</option>
<option value="">20</option>
<option value="">30</option>
</select>
</form>
JavaScript
// Product variation, quantity select dropdown
var product_selection = document.querySelector('#product_selection');
var product_variation = document.querySelector('#product_variation');
var product_quantity = document.querySelector('#product_quantity');
// Event listener to submit the form on change
product_selection.addEventListener('submit', submitAjax);
product_variation.addEventListener('change', doSubmit);
product_quantity.addEventListener('change', doSubmit);
// Submit form
function doSubmit(event) {
product_selection.dispatchEvent(new Event('submit')); // product_selection.submit();
}
// Handle ajax submit
function submitAjax(event) {
// Stop default form submit
event.preventDefault();
// Ajax request
$.ajax({
url: '/static/public/ajax/get_product_data.php',
type: 'POST',
data: $('#product_selection').serialize(),
success: function(result) {
if (result == 0) {
alert('Sorry');
} else {
setProductData(result);
}
},
error: function(jqxhr, status, exception) {
alert('Sorry');
}
})
}
// Update product details
function setProductData(result) {
$('#product_price').html(result.price_gross);
// Remove current quantity options
var product_quantity = document.getElementById("product_quantity");
for(i = product_quantity.options.length - 1 ; i >= 0 ; i--) {
product_quantity.remove(i);
}
// … reapply new quantity options
var c = 0;
for (var i = result.minimum; i <= result.maximum; i+=result.graduation) {
product_quantity.options[c] = new Option(i + ' ' + pwjs.product.unit, i);
if (result.product_quantity == i) {
var setselectedIndex = c;
}
c++;
}
// product_quantity.selectedIndex = setselectedIndex;
}
I think you would want to do this in steps so product_variation.addEventListener('change', doSomethingElse);
then your select would be something like:
<select name="product_variation">
<option data-increment="5" value="r">Red</option>
<option value="g">Green</option>
<option data-increment="3" value="b">Blue</option>
</select>
then when the product_variation changes doSomethingElse would rebuild the product_quantity select to take the increment value of the selected product_variation
As far I can see, you are using jQuery. So, Ill give you an example of how you can achieve this.
HTML
First of all, don't forget to specify the values for your select options, your values for product_quantity were empty. Also, I'd recommend to you that you create an extra option tag to be the default selected option and be able to validate your form later on.
<form action="" id="product_selection" name="product_selection">
<select name="product_variation">
<option value="">Select color</option>
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<select name="product_quantity">
<option value="">Select quantity</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
JavaScript
As for JavaScript, I'll recommend you to add the event listener for your last input, which is the product_quantity.
$("#product_selection").submit(function(e){
e.preventDefault();
var inputs = document.product_selection;
if( inputs.product_variation.value != "" && inputs.product_quantity.value != "" ){
$.ajax({
url: '/static/public/ajax/get_product_data.php',
type: 'POST',
data: $('#product_selection').serialize(),
success: function(result) {
if (result == 0) {
alert('Sorry');
} else {
setProductData(result);
}
},
error: function(jqxhr, status, exception) {
alert('Sorry');
}
});
}
});

Get data from DB based and display in textbox on selected values. laravel 5.7

I had to display data on textbox on change of select box but it will not work & also control not going to ajax url.
HTMl code:
<select class="form-control" name="product_title" id="product_title">
#foreach($product_title as $id => $p_title )
<option value="{{ $id }}">{{ $p_title }}</option>
#endforeach
</select>
<input type="text" class="form-control" name="product_price" id="product_price">
<input type="text" class="form-control" name="product_quantity" id="product_quantity">
Js:
<script>
$(document).ready(function(){
$("#product_title").change(function(){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/productdetails') }}",
method: 'get',
data: {
id: jQuery('#product_title').val()
},
success: function(result){
jQuery('#product_price').html(result.product_price);
jQuery('#product_quantity').html(result.product_quantity);
}});
});
});
</script>
route:
Route::get('/productdetails', 'ProductController#getProduct');
public function getProduct(Request $req)
{
$product = product::find($req->id)->first(); // Product is the model
//dd($product);
if ($product)
{
return response()->json(['product_price' => $product->product_price,'product_quantity' => $product->product_quantity]);
}
}
Database table name is product with attribute id,product_title,product_price,quantity.When i select title value from select box related value product_price,quantity from database will display in textbox.
Looks like issue is on success function lines. html is not useful for assign value to text. it is used to echo html. instead you can use val() like following.
jQuery('#product_price').val(result.product_price);
jQuery('#product_quantity').val(result.product_quantity);
Hope it helps. happy coding.
you can use simple without jquery like as follow
<select>
foreach($result as $key => $value)
{
echo "<option value=".$your_id_variable.">".$your_display_variable."</option>";
}

Can't call my json function in laravel 4.2

So in my 'edit records' view I have this two dropdrown the first one contains the main category and the second one should contain values based from the main category chosen is the first dropdown. So I implemented an ajax call for this in my view, here is how the dropdown code looks like
<select name="category" id="category" class="dds">
#foreach($mCategories as $lists)
<option value="{{$lists->maincategoryid}}">{{$lists->maincategoryname}}</option>
#endforeach
</select>
<h6>Doc SubClass 1</h6>
<select name="subcategory" id="subcategory" class="dds">
<option value=""></option>
</select>
then I have this in my script to call the ajax function
<script>
$('#category').on('change' , function(e){
console.log(e);
var cat_id = e.target.value;
alert(cat_id);
//ajax
$.getJSON('ajax-subcat?cat_id=' + cat_id , function(data){
console.log(data);
$('#subcategory').empty();
$.each(data, function(index, subcatObj)
{
$('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
});
});
});
</script>
and the code for the ajax call is in my routes and here is how it looks
Route::get('ajax-subcat' ,function()
{
$cat_id = Input::get('cat_id');
$subcategories = DB::table('nsa_subcategory')
->where('maincategoryid' , '=' , $cat_id)
->get();
return Response::json($subcategories);
});
as you can see, in my script I tried to log the data after the $getJSON to check whether or not it went in but I am not getting anything. The thing is I also used this codes in my creating of records so i don't know what my error is now. any ideas? thanks in advance!