Pure Javascript populate data to select options from JSON URL - javascript

I had a javascript function that pulls data from url, however im having "undefined" options when im trying to add it on the next select element.
Here is my code.
First Select element
<div class="col-sm-6">
<label class="font-bold no-margins">City/State *</label>
<select name="city_state" class="form-control required" id="city_state" onchange="populateSelect(this);">
<?php
echo '<option value="'.$city_state_data->id.'">'.$city_state_data->name.'</option>';
foreach ($city_states as $city_state) {
if($city_state_data->id != $city_state->id)
{
echo '<option value="'.$city_state->id.'">'.$city_state->name.'';
}
}
?>
</select>
</div>
Second Select element
<div class="col-sm-12 col-xs-12">
<div class="form-group has-feedback">
<label class="font-bold no-margins">Locale *</label>
<select name="locale" class="form-control required" id="locale">
<?php
echo '<option value="'.$locale_data->id.'">'.$locale_data->name.'</option>';
foreach ($locales as $locale) {
if($locale_data->id != $locale->id){
echo '<option value="'.$locale->id.'">'.$locale->name.'';
}
}
?>
</select>
</div>
Now my JS script
<script>
function populateSelect(item) {
// json url
//var url = 'citystate/' + item.value + '/locales/';
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
// empty select
document.getElementById('locale').options.length = 0;
var ele = document.getElementById('locale');
for (var i = 0; i < url.length; i++) {
// populate select element with json
ele.innerHTML = ele.innerHTML +
'<option value="' + url[i]['id'] + '">' + url[i]['name'] + '</option>';
}
}
</script>
Can you please help me how can i fix this undefined values in the select box.
Thank you.

You need to parse your JSON string if you want to access the data.
function populateSelect(item) {
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
var data = JSON.parse(url);
// empty select
document.getElementById('locale').options.length = 0;
var ele = document.getElementById('locale');
for (var i = 0; i < data.length; i++) {
// populate select element with json
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['id'] + '">' + data[i]['name'] + '</option>';
}
}
Hope it helps!

Related

Laravel: Auto populate dropdown select with AJAX is returned undefined

So I have tried auto populated dropdown in Laravel. I'm on the half way to complete this, I think so.. So basically I have 3 select dropdown list which is dependent on the first dropdown. the second dropdown list is return as expected, but the other one / the third dropdown is returned undefined list. I haven't find the solution or any clue to fix this. I hope I get the appropriate hints or directions to solve this. Thank You
Here's my dropdown in View
<div class="form-group row">
<label for="nm_cust" class="col-sm-2 col-form-label">Nama Customer</label>
<div class="col-sm-4">
<select name="nm_cust" id="nm_cust" class="form-control" required>
<option value="">Pilih</option>
#foreach ($customer['data'] as $cust)
<option value="{{ $cust->nm_cust }}">{{ $cust->nm_cust }}
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label for="alamat" class="col-sm-2 col-form-label">Alamat</label>
<div class="col-sm-4">
<select name="alamat" id="alamat" class="form-control" required>
<option value="">Pilih</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="no_psn" class="col-sm-2 col-form-label">Nomor Pemesanan</label>
<div class="col-sm-4">
<select name="no_psn" id="no_psn" class="form-control" required>
<option value="">Pilih</option>
</select>
</div>
</div>
and this is my controller
public function index()
{
$customer['data'] = Customer::orderby("nm_cust","ASC")
->select('nm_cust','alamat')
->get();
$barang = \App\Barang::All();
$pemesanan['data'] = Pemesanan::orderby("nm_cust","ASC")
->select('nm_cust','no_psn')
->get();
// $temp_kirim = Temp_pengiriman::All();
//No otomatis untuk transaksi pengiriman
$AWAL = 'DLV';
$bulanRomawi = array("", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
$noUrutAkhir = \App\Pengiriman::max('no_kirim');
$no = 1;
$no_kirim = sprintf("%03s", abs((int)$noUrutAkhir + 1)) . '/' . $AWAL . '/' . $bulanRomawi[date('n')] . '/' . date('Y');
$pengiriman = Pengiriman::orderBy('no_kirim', 'DESC')->paginate(5);
return view('pengiriman.pengiriman',
[
'no_kirim' => $no_kirim,
'customer' => $customer,
'barang' => $barang,
'pemesanan' => $pemesanan,
// 'temp_kirim' => $temp_kirim,
'pengiriman' => $pengiriman
]
);
}
public function getCustomer($nm_cust="")
{
$custData['data'] = Customer::orderby("nm_cust","ASC")
->select('nm_cust','alamat')
->where('nm_cust',$nm_cust)
->get();
return response()->json($custData);
}
public function getNoPsn($nm_cust="")
{
$noPsnData['data'] = Pemesanan::orderby("nm_cust","ASC")
->select('nm_cust','no_psn')
->where('nm_cust',$nm_cust)
->get();
return response()->json($noPsnData);
}
and this is my AJAX to get the dropdown list
<script type='text/javascript'>
$(document).ready(function() {
// Department Change
$('#nm_cust').change(function() {
// Department id
var nm_cust = $(this).val();
// Empty the dropdown
$('#alamat').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'pengiriman/' + nm_cust,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response['data'] != null) {
len = response['data'].length;
}
if (len > 0) {
// Read data and create <option >
for (var i = 0; i < len; i++) {
var nm_cust = response['data'][i].nm_cust;
var alamat = response['data'][i].alamat;
var option = "<option value='" + alamat + "'>" + alamat +
"</option>";
$("#alamat").append(option);
}
}
}
});
});
});
$(document).ready(function() {
// Department Change
$('#nm_cust').change(function() {
// Department id
var alamat = $(this).val();
// Empty the dropdown
$('#no_psn').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'pengiriman/' + alamat,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response['data'] != null) {
len = response['data'].length;
}
if (len > 0) {
// Read data and create <option >
for (var i = 0; i < len; i++) {
var alamat = response['data'][i].nm_cust;
var no_psn = response['data'][i].no_psn;
var option = "<option value='" + no_psn + "'>" + no_psn +
"</option>";
$("#no_psn").append(option);
}
}
}
});
});
});
</script>
I put that script in the views. Please help me solve this problem or give any clue to fix this.
// I forgot my route to put into this section sorry guys
And this is my routes. so I just change parameter on 3rd route below, which is name('pengiriman.getNoPsn), to /{alamat} depends on my AJAX but still no effect.
//pengiriman
Route::get('/pengiriman', 'PengirimanController#index')->name('pengiriman.pengiriman')->middleware('role:Marketing');
Route::get('/pengiriman/{nm_cust}', 'PengirimanController#getCustomer')->name('pengiriman.getCustomer')->middleware('role:Marketing');
Route::get('/pengiriman/{nm_cust}', 'PengirimanController#getNoPsn')->name('pengiriman.getNoPsn')->middleware('role:Marketing');
You don't need to call the nm_cust selector twice to get 2nd and 3rd dropdown result. As 2nd and 3rd both dropdown result depending on the num_cust selector, so you can keep both under same action. And also ensure that the AJAX URL are correct for both dropdown individually.
UPDATE:
Minimize code from your given scenario, as you have issues starting from route to controller to AJAX request. Please Follow the below steps.
Add this route in your route file.
Route::get('/pengiriman/psn-cust', 'PengirimanController#getNoPsnAndCustomer')->name('pengiriman.psn-cust')->middleware('role:Marketing');
Add this function in your controller file and don not forget to use Illuminate\Http\Request class top of your controller file.
public function getNoPsnAndCustomer(Request $request) {
$nm_id = $request->id;
$custData = Customer::orderby("nm_cust","ASC")
->select('nm_cust','alamat')
->where('nm_cust',$nm_id)
->get();
$noPsnData = Pemesanan::orderby("nm_cust","ASC")
->select('nm_cust','no_psn')
->where('nm_cust',$nm_id)
->get();
return response()->json(["nm_psn" => $noPsnData, "nm_cust" => $custData]);
}
And use this script
<script>
$(document).ready(function() {
$('#nm_cust').change(function() {
var nm_id = $(this).val();
let link = `{{ url('pengiriman/psn-cust')}}`
$('#alamat').find('option').not(':first').remove();
$('#no_psn').find('option').not(':first').remove();
$.ajax({
url: link,
type: 'GET',
data: {id: nm_id},
dataType: 'json',
success: function(response) {
if(response.nm_psn.length > 0) {
let len = response.nm_psn.length;
for (let i = 0; i < len; i++) {
let nm_cust = response.nm_psn[i].nm_cust;
let alamat = response.nm_psn[i].alamat;
let option = "<option value='" + alamat + "'>" + alamat +
"</option>";
$("#alamat").append(option);
}
}
if(response.nm_cust.length > 0) {
let len = response.nm_cust.length;
for (let i = 0; i < len; i++) {
let nm_cust = response.nm_cust[i].nm_cust;
let alamat = response.nm_cust[i].alamat;
let option = "<option value='" + alamat + "'>" + alamat +
"</option>";
$("#no_psn").append(option);
}
}
}
});
})
});
</script>

How to print value and description in selected option from Ajax JSON while page loaded

I already see data is loaded on Json/Ajax. I want to add data (value and description) in selected option. I did it this way. And all data is shown on one option tab. I am lost here. Below is the Ajax code and html.
$(function(){
categoryload();
});
function categoryload() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname = window.location.protocol + "//" + window.location.hostname+ "/sgw/modules/controller/categorycontroller.php";
alert (hosname);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data){
alert(data);
var obj = data;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#category").html(areaOption);
}
});
}
HTML
<div class="form-group">
<label class="control-label col-md-4">Service Category:</label>
<div class="col-md-7">
<select class="form-control" name="category" id="category">
<option value="0">Select Category</option>
<option value="1"> </option>
<option value="2"> </option>
</select>
</div>
</div>
Categorycontroller.php
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
$list = array();
$list[]= $category->categorylist();
$return["json"] = json_encode($list);
echo $return["json"];

Populating selected items at the right box of DualListBox

I am using this plugin to create a DualListBox for a selection field for a form in twitter-bootstrap-3. The form is created for edition purpose. So i am trying to add the previously selected values in the right-sided box. And also non-selected values are added manually.
To achieve this i have collected data from a JSON and make options string manually. Here is my code -
// Getting data related to the country of operations
$.getJSON(country_of_operation_json_url)
.done(function (data) {
var options = '';
for (var i = 0; i < data.length; i++) {
var a = 1;
for (var j = 0; j < port_ids.length; j++) {
// Appending "selected" attribute to the values which are already selected
if (port_ids[j] == data[i]["id"]) {
options += '<options value="' + data[i]["id"] + '" selected="selected">' + data[i]["port_iso"] + '</options>';
a = 0;
}
}
if (a == 1) {
options += '<options value="' + data[i]["id"] + '">' + data[i]["port_iso"] + '</options>';
}
}
// Appending the options at the selected box of the dual box
$("select#country-of-operation-edit").empty().append(options);
// Loading Country of operating dual-box field
$("#country-of-operation-edit").DualListBox();
});
Here is the html file that is generating select field -
<div class="form-group row">
<label class="col-sm-2 form-control-label">Country of operation</label>
<div class="col-sm-10">
<select class="form-control" multiple="multiple" data-json="false" id="country-of-operation-edit">
</select>
</div>
</div>
Problem is there are no values showing in the field. Here is the screenshot -
I couldn't find what am i doing wrong here. If this is not the way to populate the DualListbox with values, what are the other ways? Any help would be appreciated much. I am stuck here for hours.
EDIT-1: Here is my json - http://codebeautify.org/jsonviewer/cb7e1573
EDIT-2: For checking, you can take this values as selected -
port_ids = ["41", " 47", " 61"]
Change options to option man :)
for (var i = 0; i < data.length; i++) {
var a = 1;
for (var j = 0; j < port_ids.length; j++) {
// Appending "selected" attribute to the values which are already selected
if (port_ids[j] == data[i]["id"]) {
options += '<option value="' + data[i]["id"] + '" selected="selected">' + data[i]["port_iso"] + '</option>';
a = 0;
}
}
if (a == 1) {
options += '<option value="' + data[i]["id"] + '">' + data[i]["port_iso"] + '</option>';
}
}
https://jsfiddle.net/hh2zrt82/

Jquery append html weird behavior

i have the following ajax:
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/ajax_get_subcategories',
dataType: 'json',
data: {
id: id
},
success: function (data) {
var length = data.length;
var div_subcategory = $('#subcategory');
div_subcategory.html('');
div_subcategory.append(
"<select id='subcategory' name='data[Product][subcategory_id]'>"
);
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
$('#subcategory').append(
"<option value=''+id>" + name + "</option>"
);
}
div_subcategory.append("</select>");
}
});
Now as you can see it appends a select into a div block.
But! there is a catch here is the output of the HTML after the ajax has been called:
div id="subcategory" class="subcategory">
<select id="subcategory" name="data[Product][subcategory_id]"></select>
<option +id="" value="">Telte</option>
<option +id="" value="">Toilet</option>
<option +id="" value="">Service</option>
<option +id="" value="">Borde</option>
<option +id="" value="">Stole</option>
<option +id="" value="">Lyd og lys</option>
</div>
As you can see it closes the select tag before adding the options.
Can anyone tell me why this is happening?
When you write:
div_subcategory.append("<select id='subcategory' name='data[Product][subcategory_id]'>");
jQuery will insert
<select id='subcategory' name='data[Product][subcategory_id]'></select>
And becasue div_subcategory will have the same id as the select you will be matching the div instead.
Instead I would write this by creating the html in a string and injecting it all at once.
var html += "<select id='subcategorysel' name='data[Product][subcategory_id]'>";
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
html += "<option value=''+id>" + name + "</option>";
}
html += "</select>";
div_subcategory.append(html);
This snippet updates your code to use different ids and appends the html all in one go which should be quicker.
Try
change your success code
success: function (data) {
var length = data.length;
var div_subcategory = $('#subcategory');
div_subcategory.html('');
var select_append = "<select id='subcategory' name='data[Product][subcategory_id]'>";
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
select_append += "<option value=''" + id + ">" + name + "</option>";
}
select_append += "</select>"
div_subcategory.append(select_append);
}
create a variable select_append and concatenate all your code in that and append that variable in the end.
Try
$(div_subcategory).find('select').append(...)
when you write this syntex
div_subcategory.append(
"<select id='subcategory' name='data[Product][subcategory_id]'>"
);
DOM automatically detects an HTML element like this
<select id='subcategory' name='xxx'></select>
and then you are appending other option elements after this
so solution is first make a string of an HTML and then append like
var html = "<select id='subcategory' name='data[Product][subcategory_id]'>";
for (var i = 0; i < length; i++) {
var id = data[i]['Subcategory']['id'];
var name = data[i]['Subcategory']['name'];
html += "<option value='' + id>" + name + "</option>";
}
div_subcategory.append(html);

handling 2 different select option which were just appended with jquery

first thank to this question https://stackoverflow.com/questions/14792014/select-option-which-were-just-appended-with-jquery
i have another problem when option value from spilting data on sql result there are two select in one page.
Here my code
as default page
<div>
Warehouse Product
<br><input type="text" id="wh" readonly/>WHK</br>
</br>
Nomor Rak
<br><input type="text" id="posisi" readonly/></br>
Product Kategori
<br><select id="pkategori">
<option selected = "selected" value = "option1">-Kategori Produk-</option>
<?php
$q = mssql_query("SELECT DISTINCT ProductCategory from tblMstProductUHT1");
while ($r = mssql_fetch_array($q)){
echo "<option value='$r[ProductCategory]'>$r[ProductCategory]</option>";
}?>
</select>
</br>
Nama Produk
<br><select id="pname">
<option selected = "selected" value="option1" >-Nama Produk-</option>
<?php
$q = mssql_query("SELECT DISTINCT ProductName from tblMstProductUHT1");
while ($r = mssql_fetch_array($q)){
echo "<option value='$r[ProductName]'>$r[ProductName]</option>";
}?>
</select>
</br>
Kode Produksi
<br><input type='text' id="pdate"></br>
Line/FM
<br><input type='text' id="line"></br>
Nomor Palet
<br><input type="text" id="pnumber"/>
</br>
Nomor Seri Produk
<br><input type='text' id="seri"></br>
Quantity(Carton)
<br><input type='text' id="quantity"></br>
<button id="save">Save</button>
<button id="edit">Edit</button>
<button id="view">View</button>
<button id="delete">Delete</button>
</div>
you see there two select option <select id="pkategori"> and <select id="pname">. Now for Edit button i call available data using ajax like below
$("#edit").click(function(){
posisi = $("#posisi").val();
$.ajax({
type:'POST',
url: "aksi.php",
data: "op=edit&posisi="+posisi,
cache: false,
success: function(msg){
if(msg=="error"){
$(".status").html("<font color='##480000'><strong> Data tidak ditemukan..! </strong></font>");
}
else{
//karna di server pembatas setiap data adalah |
//maka kita split dan akan membentuk array
data = msg.split("|");
//masukkan ke masing-masing textfield
var r = [data[0]];
options = [{id:0, value:r}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pkategoriOption_' + data['id'] + '" class="pkategori" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pkategori').append(option);
}
$("#pkategori .pkategori:first").prop('selected', true);
var s = [data[1]];
options = [{id:0, value:s}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pnameOption_' + data['id'] + '" class="pname" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pname').append(option);
}
$("#pname .pname:first").prop('selected', true);
$("#pdate").val(data[2]);
$("#pnumber").val(data[3]);
$("#seri").val(data[4]);
$("#quantity").val(data[5]);
$("#line").val(data[6]);
//hilangkan status dan animasi loading
$(".status").html("");
$(".loading").hide();
}
}
});
});
on url: "aksi.php", i split data using "|". According to the question that i linked in first. I succesfull append option value on <select id="pkategori"> and set this as default selected.
But when i use the same code for the second option <select id="pname"> it's caused error and data that i split doesn't show. so i stuck, what the problem?
actually your linked have the answer. in your code you just have similar var. mean on "data", it's cause conflict. Jquery will confuse to bind data,
so you just change data = msg.split("|"); to another name variable.
Your code will be like below
$("#edit").click(function(){
posisi = $("#posisi").val();
$.ajax({
type:'POST',
url: "aksi.php",
data: "op=edit&posisi="+posisi,
cache: false,
success: function(msg){
if(msg=="error"){
$(".status").html("<font color='##480000'><strong> Data tidak ditemukan..! </strong></font>");
}
else{
//karna di server pembatas setiap data adalah |
//maka kita split dan akan membentuk array
da = msg.split("|"); // it can be another variable name
//masukkan ke masing-masing textfield
var r = [da[0]];
options = [{id:0, value:r}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pkategoriOption_' + data['id'] + '" class="pkategori" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pkategori').append(option);
}
$("#pkategori .pkategori:first").prop('selected', true);
var s = [da[1]];
options = [{id:0, value:s}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pnameOption_' + data['id'] + '" class="pname" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pname').append(option);
}
$("#pname .pname:first").prop('selected', true);
$("#pdate").val(da[2]);
$("#pnumber").val(da[3]);
$("#seri").val(da[4]);
$("#quantity").val(da[5]);
$("#line").val(da[6]);
//hilangkan status dan animasi loading
$(".status").html("");
$(".loading").hide();
}
}
});
});

Categories

Resources