how to take data[index] value in ajax? - javascript

Sorry but it's my first time with javascript and ajax
I have this code where i print a list from db in an html select
ajax
'''
$.ajax({
type: 'GET',
url: 'birthplace/list',
dataType: 'json',
success: function(data) {
$.each(data, function(i) {
$('#selectBirthplace').append(
'<option id="' + data[i] + '" value="' + data[i] + '">'
+ data[i].nome + '</option>'
);
});
}
});
'''
html
'''
<div class="item3">
<label for="">Birthplace</label>
<select required class="custom-input" id="selectBirthplace" >
<option value="" selected disabled hidden>Select birthplace</option>
</select>
</div>
'''
Birthplace is a parameter of User but it's still a class.
This is part of a user insert form page.
How can i save the value of data[i] in a variable when the select option was chosen?
i tried with data[i].variable, data[i].class but nothing.

Related

Making of an option selected in ajax call not working

I have tried below lines of code for making an option selected if it matches with the data's DepartmentName. It's not working. Please help !!!
function fillDepartments(selectedText)
{
$.ajax({
url: 'index.php?action=fetchAllDepartments',
type: 'POST',
dataType: 'JSON',
data:{},
success: function(data){
for(var i in data){
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
+ data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +
'</option>');
}
}
});
}
Apply a simple if-else condition:-
for(var i in data){
if(selectedText == data[i]['DepartmentName']){
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '" selected>'+ data[i]['DepartmentName']+'</option>');
}else{
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'+ data[i]['DepartmentName'] +'</option>');
}
}
seems like problem with below code where you are closing tag without including select in it
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
//error as its out of opening bracket
+ data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +'</option>');
you need to include selected in bracket5
<option value='abc' selected></option>
in your case it is
<option value='abc' > selected</option>//wrong

How to avoid ajax result on select box

As you in sample above I have placeholder (option without value) to say eg. Select Subcategory but as soon as I change my category value result of subcategories will show.
What I want is when I select category in subcategory dropdown still says Select Subcategory but under that be loaded result of chosen category. In simple words:
Instead of showing results directly, shows placeholder option and
results be under it.
here is my codes:
// HTML
<label for="specification_id">specifications</label>
<select name="specification_id" class="form-control">
<option value="">Select Specification</option>
</select>
// JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('select[name="subcategory_id"]').on('change', function() {
var subcategoryID = $(this).val();
if(subcategoryID) {
$.ajax({
url: '{{ url('getspecifications') }}/'+encodeURI(subcategoryID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="specification_id"]').empty();
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+ value['id'] +"'>"+ value['title'] +"</option>"
);
});
}
});
}else{
$('select[name="specification_id"]').empty();
}
});
});
</script>
After emptying out the item make sure to append the blank placeholder back in it:
else{
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
}
or just skip it when clearing the select in the first place:
else{
$('select[name="specification_id"]').not(':first').remove();
}
i forgot the empty() in the success: function:
success:function(data) {
$('select[name="specification_id"]').not(':first').remove();
//...
or:
success:function(data) {
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
//...
Here your option values are empty because you Call empty function.
So you can dynamically select option "Select specification "
Following procedure works fine for me, try this way
success:function(data) {
$('select[name="specification_id"]').empty();
$('select[name="specification_id"]').append("<option
class='form-control' selected value=' '>Select
Specification </option>" );
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+
value['id'] +"'>"+ value['title'] +"</option>"
);
});
Thank you

laravel ajax sending and returning at the same page

What I'm trying to do is to create one-page checkout, and the part i get my courier cost i'm facing issue.
I want to send destination city id to controller and get back cost result from controller in order to let user select which way he/she wants to ship his/her product.
Sample from some live website:
Imgur
Ibb
I'm using third-party website data, nothing stored in my database such
as country province city methods or even shipping prices
codes:
My page index function (where everything will show
public function index(Request $request) {
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxx');
$province = $rajaongkir->province();
return view('front.raja', compact('province'));
}
route of it:
Route::get('/raja', 'RajaongkirController#index')->name('raja');
My cities function (where i get cities list based on province selected):
public function getCityList($province)
{
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxx');
$city = $rajaongkir->city($province);
return response()->json($city);
}
route of it:
Route::get('/get-city-list/{province}','RajaongkirController#getCityList');
Cost data function (here is where supposed to return price methods base on selected city):
public function indexajax(Request $request, $cityID) {
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxx');
$province = $rajaongkir->province();
$origin = 152; //Jakarta
$destination = $request->cityID;
$weight = 1;
$courier = 'tiki'; // jne, tiki, pos
$cost = $rajaongkir->cost($origin, $destination, $weight, $courier);
return view('front.raja', compact('province', 'cost'));
}
route of it:
Route::get('/rajaajax/{cityID}', 'RajaongkirController#indexajax');
PS: City Id that comes from ajax supposed to be value of
$destination where i put $destination = $request->cityID;
view
this part shows 2 select input where i choose provinces and cities
//HTML
<select name="province" id="">
<option class="form-control" value="">Select Province</option>
#foreach ($province->data as $info)
<option value="{{$info->province_id}}">{{$info->province}}</option>
#endforeach
</select>
<select name="city" id="">
<option class="form-control" value="">Select City</option>
</select>
//JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('select[name="province"]').on('change', function() {
var provinceID = $(this).val();
if(provinceID) {
$.ajax({
url: '{{ url('get-city-list') }}/'+encodeURI(provinceID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data.data, function(key, value) {
$('select[name="city"]').append('<option id="city_id" class="form-control" value="'+ value['city_id'] +'">'+ value['city_name'] + ' - ' + value['type'] +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
Cost view codes
here is my loop to show costs when have city id (tested on static $destination id)
Destination:
{{$cost->meta['destination']->province}}, //destination province
{{$cost->meta['destination']->type}}, //destination type such as city or restrict
{{$cost->meta['destination']->city_name}}, //destination city name
{{$cost->meta['destination']->postal_code}}. //destination postal code
#foreach($cost->data as $option)
<h3>{{$option->code}} <small>{{$option->name}}</small></h3>
#foreach($option->costs as $cost)
#foreach($cost->cost as $c)
<label class="radio">
<input name="post" value="{{ $c->value }}" type="radio">{{$cost->service}} / {{ $c->value }} Rp - {{ $c->etd }} hari #if(!empty($c->note))- {{ $c->note }} #endif
</label>
#endforeach
#endforeach
#endforeach
Result will be like so:
PS:: I think: Cost part must be looped in controller because when i
put it in blade (and user didn't choose city yet, it gives error of
undefined/non-object cost) - Just thought :)
Anyone has idea how can i get that cost part after choosing city?
SOLVED
I've changed my cost to:
return response()->json($cost);
And added this JS to my view:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
console.log();
$('#info').append('<h3>'+ value['code'] + '<small>' + value['name'] +'</small></h3>');
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value2['service'] + ' - ' + value3['value'] + ' - ' + value3['etd'] +'</option>');
});
});
});
}
});
}else{
console.log(data);
}
});
});
</script>
Also Added this to my view:
<div id="calcul" style="margin-top: 30px;">
<div id="des"></div>
<dev id="info"></dev>
<select name="postchoose" id="">
<option class="form-control" value="">Select Shiping Method</option>
</select>
</div>
However I would like to have radio button instead of drop-down but is OK :).
Hope it help others.

on change from jquery is not doing what it supposed to do

I have 4 Ajax Scripts that update chained dropdowns based on other one selections
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#building');
//request the JSON data and parse into the select element
$.ajax({
url: '/api/get_building/',
dataType:'JSON',
success:function(data){
//clear the current content of the select
//iterate over the data and append a select option
$.each(data, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
function getunit() {
//get a reference to the select element
$select = $('#unit');
$id_lease = $('#id_lease');
$id_leaseterm = $('#id_leaseterm');
//request the JSON data and parse into the select element
var c_id = ($("select[name='building'] option:selected").attr('value'));
c_url = "/api/get_unit/"+c_id+"/";
$.ajax({
url: c_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1"> Select unit </option>');
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
getlease();
},
});
}
function getlease() {
//get a reference to the select element
$select = $('#id_lease');
$id_leaseterm = $('#id_leaseterm');
//request the JSON data and parse into the select element
var s_id = ($("select[name='unit'] option:selected").attr('value'));
s_url = "/api/get_lease/"+s_id+"/";
$.ajax({
url: s_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1"> Select lease</option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
function getleaseterm() {
//get a reference to the select element
$select = $('#id_leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
//var l_id = 13;
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
</script>
And the following controls in my form I am updating
<select name="building" id="building" onchange="getunit();">
<option id="-1">Select building</option>
</select>
<select name="unit" id="unit" onchange="getlease();">
<option id="-1">Select unit</option>
</select>
<select class="select" id="id_lease" name="lease">
<option value="" selected="selected">---------</option>
</select>
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="" selected="selected"></option>
</select>
My problem is that when I update the dropdown id_lease it dosent have the on change call. (it is automatically generated from backend)
So for this reason I am adding this line with jquery line in script
$("#lease_id").on("change", getleaseterm());
but it gives me an error 404 that cannot find the values for "get_leaseterm" since I assume it get triggered when page is loading. And all my script are not loading.
So problem is in this last line. How can I solve it?
As Pointy specified removing the () helped as well I was calling wrong id
final version that worked is:
$("#id_lease").on("change", getleaseterm);

How to make multiple dependent dropdowns using jquery + ajax

I'm trying to build a page where users can give worksheets to each other.
I am trying to do it with dependent dropdowns. Not sure if that is the right term for it so I will provide an example.
Roughly the set categorizations is as follows:
Types > Categories > Topics > Sheets
Roughly my idea is:
Page loads json for types and displays type dropdown
User sees Math, Science, English as Types and Picks Math
Page uses ajax to query database and populates Topics with grade 1, 2, 3, etc.
User picks grade 4
Page uses ajax to query database and populates with appropriate grade 4 topics
... and so on until the bottom of the chain
In the javascript section:
<script type="text/javascript" language="javascript">
var types;
var categories;
var topics;
var sheets;
//load the first types
$(document).ready(function(){
$.ajax({
async: false,
url: "base_url/json_get_all_wstypes",
type: 'POST',
dataType: 'json',
success: function(output_string){
types = output_string;
}
});
});
//by default - intialize types
$(document).ready(function(){
var t_choices = "<select name=\"type_id\" id=\"type_picker\" >";
t_choices += "<option value=\"\" selected=\"selected\">Select a Type</option>";
$.each(types, function(){
t_choices += "<option value=\"" + this.type_id.toString() + "\">";
t_choices += this.type_name.toString();
t_choices += "</option>";
});
t_choices += "</select>";
$('#type_choices').text('');
$(t_choices).appendTo('#type_choices');
});
//reaction to picking a type
$(document).ready(function(){
$('#type_picker').change(function(){
var url_arg = $('#type_picker').val().toString();
var full_url = "base_url/json_get_wscategories_by_type/" + url_arg;
$.ajax({
async: false,
url: full_url,
type: 'POST',
dataType: 'json',
success: function(output_string){
categories = output_string;
}
});
var choices = "<select name=\"category_id\" id=\"category_picker\" >";
choices += "<option value=\"\" selected=\"selected\">Select a category</option>";
$.each( categories, function() {
choices += "<option value=\"" + this.category_id.toString() + "\">";
choices += this.category_name.toString();
choices += "</option>";
});
choices += "</select>";
alert(choices.toString());
$('#category_choices').text('');
$(choices).appendTo('#category_choices');
});
});
//reaction to picking a category (initialize topic)
$(document).ready(function(){
$('#category_picker').change(function(){
var url_arg = $('#category_picker').val().toString();
var full_url = "base_url/json_get_wstopics_by_category/" + url_arg;
$.ajax({
async: false,
url: full_url,
type: 'POST',
dataType: 'json',
success: function(output_string){
topics = output_string;
}
});
var choices = "<select name=\"topic_id\" id=\"topic_picker\" >";
choices += "<option value=\"\" selected=\"selected\">Topic a category</option>";
$.each( topics, function() {
choices += "<option value=\"" + this.topic_id.toString() + "\">";
choices += this.topic_name.toString();
choices += "</option>";
});
choices += "</select>";
alert(choices.toString());
$('#topic_choices').text('');
$(choices).appendTo('#topic_choices');
});
});
//reaction to picking a topic (initialize sheet)
similar code pattern as method before it...
//reaction to picking a sheet (intialize page)
similar code pattern as the method before...
</script>
In the webform section:
<p>
<label for="type_id">Pick a sheet type:</label>
<div id="type_choices">
</div>
</p>
<p>
<label for="categories_id">Pick a category:</label>
<div id="category_choices">
</div>
</p>
<p>
<label for="topic_id">Pick a topic:</label>
<div id="topic_choices">
</div>
</p>
<p>
<label for="worksheet_id">Pick a worksheet:</label>
<div id="sheet_choices">
Please select a topic first to activate this section
</div>
</p>
This works for selecting the types and loads up the display for categories but once I select categories nothing happens. Also, if anyone could point me to what is called in the web world, I would be quite thankful. Dynamic dependent dropdown weren't that helpful and I'm not sure what else to call this.
Your code is unnecessarily dependent on jQuery and doesn't re-use code effectively. This solution may require a subtle rewrite of your server side code, but that should be more abstracted anyway. Try something more like this:
<html>
<body>
<select id="type" onchange="updateNext(this, 'category')">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select id="category" onchange="updateNext(this, 'topic')">
</select>
<select id="topic" onchange="updateNext(this, 'worksheet')">
</select>
<script>
function updateNext(el, nextName) {
var url_arg = el.value;
var full_url = "base_url/json_get_wstopics_by_category/" + url_arg;
var options, txtStrng;
//grab ajax data
$.ajax({
async: false,
url: full_url,
type: 'POST',
dataType: 'json',
success: function(output_string){
options= output_string;
}
});
//create the option list
$.each( options, function() {
txtStrng += "<option value=\"" + this.option_id.toString() + "\">";
txtStrng += this.option_name.toString();
txtStrng += "</option>";
});
//clear the option list
$('#'+nextName).text('');
//attach the option list
$(txtStrng).appendTo('#'+nextName);
}
</script>

Categories

Resources