I am writing a ajax program in which I am reading data from files created in the project folder. I am having trouble when I select Pakistan country then select any province. Firstly cities in selected province come but when I change the Province all the cities in all province files come. I am trying for hours but not able to figure out. Please anyone can help
Here is my jQuery/ajax code:
switch (myProvince) {
case 'Pakistan':
$.ajax({
type:"GET",
url: "file/country/Pakistan.txt",
dataType: "text",
success: function (response) {
var arrayProvince = response.split(',');
for (var i = 0; i < arrayProvince.length; i++) {
$('#province').append('<option>' + arrayProvince[i] + '</option>');
}
}
});
$('#province').change(function () {
var myCity = $('#province option:selected').text();
$("#city").find("option:not(:first)").remove();
switch (myCity) {
case 'KPK':
$.ajax({
type: "GET",
url: "file/Province/KPK.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var j = 0; j < arrayCity.length; j++) {
$('#City').append('<option>' + arrayCity[j] + '</option>');
}
}
});
case 'Punjab':
$.ajax({
type: "GET",
url: "file/Province/Punjab.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
case 'Balochistan':
$.ajax({
type: "GET",
url: "file/Province/Balochistan.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
case 'Kashmir':
$.ajax({
type: "GET",
url: "file/Province/Kashmir.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
case 'Sindh':
$.ajax({
type: "GET",
url: "file/Province/Sindh.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
default:
}
});
Here is my Html code.
<div class="row">
<div class="col-sm-4 form-group">
<select class="country form-control" id="country">
Country
<option disabled selected>Country</option>
<option>Pakistan</option>
<option>America</option>
<option>Russia</option>
<option>China</option>
</select>
</div>
<div class="col-sm-4 form-group">
<select class="country form-control" id="province">
<option id="proDefault" disabled selected>State/Province</option>
</select>
</div>
<div class="col-sm-4 form-group">
<select class="country form-control" id="City">
<option id="city" disabled selected>City</option>
</select>
</div>
</div>
You need a break; at the end of each case block.
See: https://www.w3schools.com/js/js_switch.asp
I removed your switch from province selection. You can do the same for countries, so your code will be significantly shorter with no duplication and much easier to maintain.
Plunker
$(function() {
$('#country').change(function() {
$.ajax({
type: "GET",
url: "Pakistan.txt",
dataType: "text",
success: function(response) {
var arrayProvince = response.split(',');
for (var i = 0; i < arrayProvince.length; i++) {
$('#province').append('<option>' + arrayProvince[i] + '</option>');
}
}
});
});
$('#province').change(function() {
var myCity = $('#province option:selected').text();
$.ajax({
type: "GET",
url: myCity + ".txt",
dataType: "text",
success: function(object) {
$("#city").find("option:not(:first)").remove();
var arrayCity = object.split(',');
for (var j = 0; j < arrayCity.length; j++) {
$('#city').append('<option>' + arrayCity[j] + '</option>');
}
}
});
});
});
Related
I'm implementing default edit mode on razor view. All things works except the filling function for drop-down list . Regarding my work i have to fill my state drop-down list based on current selected country value at on load event. To accomplish ,i have implemented ajax inside a for loop.
razor
#foreach (CustomerModel customer in Model)
{
<tr>
<td class="CustomerId">
<span id="spn_#customer.CustomerId">#customer.CustomerId</span>
</td>
<td class="Name">
#Html.TextBoxFor(model => customer.Name,new { id = "txtName_" + #customer.CustomerId , onkeyup = "getID(this.id)" })
#*<input id="txtName_#customer.CustomerId" type="text" onkeyup="getID(this.id)" value="#customer.Name"/>*#
</td>
<td class="State">
<select id="ddlState_#customer.CustomerId" style="width:200px;">
#*<option>#customer.StateName</option>*#
</select>
</td>
<td class="Country">
<select id="ddlCountry_#customer.CustomerId" onfocus="fillCountry(this.id)" onchange="fillState(this.id,this.value)" style="width:200px;">
<option>#customer.CountryName</option>
</select>
</td>
<td>
<button id="#customer.CustomerId" onclick="update(this.id)">Save</button>
</td>
</tr>
<script>
arrayID.push('#customer.CustomerId');
</script>
}
Script
var ids;
var txtName;
var txtCountry;
var onchangeFlag = 0;
s = 0;
var idOf;
var idArray = [];
var length = 2;
var flag = 1;
$(document).ready(function () {
// alert(arrayID);
var ido;
var ddlCountryID;
var index = 0;
var countryValue;
var ddlStateidElement;
var s = 0;
var ddlStateID;
var lenthof = arrayID.length;
for (var i = 0; i < lenthof; i++) {
// alert(lenthof);
ido = arrayID[i];
//index = ido;
ddlCountryID = "ddlCountry_" + ido;
ddlStateID = "ddlState_" + ido;
countryValue = $('#' + ddlCountryID).val();
// alert(countryValue);
$.ajax({
type: "POST",
url: "/New/GetOnState",
contentType: "application/json; charset=utf-8",
data: '{"country":"' + countryValue + '"}',
dataType: "html",
success: function (result, status, xhr) {
// alert("success");
// alert(arrayID[index]);
ddlStateidElement = "ddlState_" + ido;
$('#' + ddlStateidElement).html(result);
//index = index + 1;
},
error: function (xhr, status, error) {
alert("Enter");
}
});
//loopend
}
Both c# code and ajax always successful still the loop index always points the last index of the array, i don't know why the loop index fails.
output
$.ajax({
type: "POST",
url: "/New/GetOnState",
contentType: "application/json; charset=utf-8",
data: '{"country":"' + countryValue + '"}',
dataType: "html",
async:false,
success: function (result, status, xhr) {
// alert("success");
// alert(arrayID[index]);
ddlStateidElement = "ddlState_" + ido;
$('#' + ddlStateidElement).html(result);
//index = index + 1;
},
error: function (xhr, status, error) {
alert("Enter");
}
});
I need to fetch data from multiple API and display them in the table.
What I came up with is:
var req = $.ajax({
url: "....linkhere",
dataType: 'jsonp'
});
var req = $.ajax({
url: "....linkhere1",
dataType: 'jsonp'
});
req.done(function(data) {
console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Although, this way I can only get data from one api. How can I take it from multiple?
EDIT:
I am trying to add text input, so I can send request about specific word. I am trying to append existing table with new results. I was trying to alter code which was provided as an answer below. However, I did something work, and it does not work.
$("#inputChoice").on("blur", function() {
let choice = $(this).val();
let req = $.ajax({
url: "...APIlink"+choice,
dataType: "jsonp"
});
req.done(function (data) {
console.log(data);
var infoTable = $("<table />");
let arrayL = data.length;
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
titleCell.addClass("title-row");
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
detailCell.addClass("details-row")
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Request data from endpoints and when they're all done create a table
function multiReq(...links) {
let responseCount = links.length;
const responses = [];
let handler;
function responseHandler(i) {
return data => {
responseCount -= 1;
responseCount === 0
? handler([].concat(...responses))
: (responses[i] = data)
}
}
links.forEach((link, i) => $.ajax({
url: link,
dataType: 'jsonp'
}).done(responseHandler(i)));
return {
done(callback) {
handler = callback;
}
};
}
multiReq(link1, link2).done((data) => {})
or
function multiReq(...links) {
return Promise.all(links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses))
}
multiReq(link1, link2).then(data => {
// create table
})
or
function multiReq(...links) {
return $.when(...links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses.map(([data]) => data)))
}
multiReq(link1, link2).done(data => {
// create table
})
or as close to your code as possible:
var req1 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
var req2 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
$.when(req1, req2).done(function([data1], [data2]) {
var data = data1.concat(data2); // merge data from both request into one
//console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display-resources"></div>
here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});
I'm trying to build mutiple select boxes that dymaically populate then next select box based on the option selected.
it seems to be working but the 3rd select box has duplicate results and i can't see why
here is the JS
$(document).ready(function() {
$('.selectchange').one('change', function() {
var x = $(this).children(":selected").attr("value");
console.log(x)
$.ajax({
type: "POST",
data: "id=" + x,
url: "../complaints/index.php/complaint/get_complaint_sub_types",
dataType: "json",
success: function(data) {
var x = $(this).children(":selected").attr("id");
$.each(data, function(id, value) {
var opt = $('<option />');
opt.val(value.id);
opt.text(value.name);
$('.selectchange1').append(opt);
$('.selectchange2').one('click', function(event) {
var y = $(this).children(":selected").attr("value");
$.ajax({
type: "POST",
data: "id=" + y,
url: "../complaints/index.php/complaint/get_complaint_description",
dataType: "json",
success: function(data1) {
if (data1 != " ") {
var z = $(this).children(":selected").attr("id");
console.log(z);
$.each(data1, function(id, value) {
var opt = $('<option />');
opt.val(value.id);
opt.text(value.name);
$('.selectchange2').append(opt);
})
};
}
})
});
});
}
});
});
})
here is the jsfiddle http://jsfiddle.net/7mg3ume5/2/
I am trying to send the following values from view to controller
var ParamAliasArray = new Object();
for (var i = 1; i <= 1; i++) {
ParamAliasArray[i] = $("#txtParamAlias" + i).val();
}
var ParamValueArray = new Object();
for (var i = 1; i <= 4; i++)
{
ParamValueArray[i] = new Array();
for (var j = 1; j <= 1; j++) {
ParamValueArray[i][j] = $("#txtParamValue" + i).val();
}
}
one is 1D array and other is 2D array I am passing as
jQuery.ajaxSettings.traditional = true
$.ajax({
type: 'Post',
dataType: 'json',
url: 'Register/GetRegDataFromuser',
data: JSON.stringify({ GloabalAppID: GlobalAppID,
TransactionID: TransactionID,
OwnerID: OwnerID,
ParamAliasArray: ParamAliasArray,
ParamValueArray: ParamValueArray }),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
console.debug(data);
},
error: function (data) {
console.debug(data);
}
});
I have written Action method as in
public ActionResult GetRegDataFromuser(int GloabalAppID, int TransactionID, string OwnerID, string[] ParamAliasArray, string[][] ParamValueArray)
{
---some logic--
}
So,I am not able to pass the array to the action method from View..Please help me out.
Thanks in advance.
you need to add ParamValueArray[i][j]=new Array(); this line.