How to get data from webservice in jquery? - javascript

I have a web service with link: http://41.128.183.109:9090/api/data/getalllocations
I recived this data in dropdown using jquery .this data contains 2 objects LocationName and LocID. I want to display an alert with LocID in dropdown change function in jQuery. Here is my code:
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value?' + i + '?="">' + data[i].LocationName + '</option>');
}
}
});
});
$("#countries").change(function () {
alert();
});
Here is my HTML code :
<select tabindex="-1" class="select2_group form-control" style="display: normal; width: 290px;" name="countries" id="countries">
<optgroup label="Select Your City" id="main"></optgroup>
</select>

please try following
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value="' + data[i].LocID + '">' + data[i].LocationName + '</option>');
}
}
});
$("#countries").change(function () {
alert($("#countries").val());
});
});

Related

Display value in dropdown based on first dropdown

I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>
First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

Data is duplicated when click again in button in javascript

I'm able to display all data, but when I click again in My team the data is displayed twice. Clicking again and again means more times the data is displayed. How can I display data once? I mean just the 6 team members and no 6 team members repeated.
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
var data1 = "TEAMSEARCH";
$.ajax({
url: 'TeamAssignment',
type: 'POST',
data: {
data1: data1
},
success: function(result) {
var memberList = $.parseJSON(result);
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName);
document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
}
}
});
}
<div class="col-lg-3 mb-0" style="display: flex;align-items: center;">
<div class="popup" onclick="myFunction()">
<h6>My team</h6>
<span class="popuptext" id="myPopup">My team members:<br><h7 id="demo"></h7><br></span>
</div>
</div>
</div>
<ol class="breadcrumb"></ol>
You need to clear demo element, before starting the for loop:
success: function(result) {
var memberList = $.parseJSON(result);
document.getElementById("demo").innerHTML = '';
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName);
document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
}
}
Personally, i prefer following code instead, when working with jquery:
$.ajax({
url: 'TeamAssignment',
type: 'POST',
data: {
data1: data1
},
dataType: "json",
success: function(memberList) {
$("#demo").html('');
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName);
$("#demo").append('<li style="list-style:none;">' + memberList[i].fullName + '</li>');
}
}
});

Populating select box options from previous select box value

I am getting problem while populating select box options depend on previous select box
Problem is Whenever I select the value from first select box (i.e. #city) it gives me the result of city value which is fine but as soon as I select the second value it gives me the result of second values as well as first values.
below is my code
HTML CODE
<lable>City</lable>
<select id="city" style="width:100%;text-align:left;" onchange="getSchool()"></select>
<span id='paymentform_city_errorloc' class='error'></span>
<br>
<br>
<lable>School</lable>
<select id="school" style="width:100%;">
</select>
<span id='paymentform_school_errorloc' class='error'></span>
<br>
<br>
JS CODE
var cityname, city, schoolname, schooldata, cityid, city1;
var cityarray = [];
var schoolarray = [];
function getCity() {
jQuery.ajax({
url: baseurl + "getcity.php",
async: true
, success: function (data) {
data = $.trim(data);
if (data == "false") {
console.log(data);
} else {
var myArray = jQuery.parseJSON(data);
jQuery(myArray).each(function (index, element) {
cityname = element.cityname;
cityid = element.city_id;
cityarray.push([cityname, cityid])
});
for (var i = 0; i < cityarray.length; i++) {
city1 += '<option value="' + cityarray[i][1] + '">' + cityarray[i][0] + '</option>';
}
$('#city').html("<option disabled selected></option>" + city1);
}
}
});
}
function getSchool() {
var city_id = $('#city').val();
jQuery.ajax({
url: baseurl + "getschool.php"
, data: 'cityid=' + city_id
, type: "POST"
, success: function (response) {
response = $.trim(response);
if (response == "false") {
$('#school').prop('disabled', 'disabled');
} else {
$('#school').prop('disabled', false);
console.log(response);
$('#school').append(response);
}
}
, error: function () {}
});
}
function getSchool() {
var city_id = $('#city').val();
schoolarray = []; //Add this code.
Make the above change. And your school array will reset every-time a new city is selected.

Categories

Resources