How to Bind to DropDown using Jsonp response? - javascript

Hi i am using jQuery Ajax to bind data to dropdown.I am using arcgis rest services as source.I am able to get response but not able to bind to dropdown.Can anybody help this done.
$.ajax({
url: "url",
data: { f: "json", where: "1 = 1 ", returnGeometry: false },
dataType: "jsonp",
success: function(response) {
console.log( response );
var len = response.length;
$("#ddlDistrict > option").remove();
$('#ddlDistrict').append("<option value='-- Select --'>-- Select --</option>");
for (var i = 0; i < len; i++) {
$('#ddlDistrict').append('<option value="' + response[i].DistrictName + '">' + response[i].DistrictName + '</option>');
}
}
});
My console output is

success: function(response) {
console.log( response, typeof response );
if(typeof response == 'string') {
response = JSON.parse(response);
}
var len = response.features.length;
$("#ddlDistrict > option").remove();
$('#ddlDistrict').append("<option value='-- Select --'>-- Select --</option>");
for (var i = 0; i < len; i++) {
console.log(response.features[i]);
$('#ddlDistrict').append('<option value="' + response.features[i].DistrictName + '">' + response.features[i].DistrictName + '</option>');
}
}

From the response it seems you want to display displayFieldName which has a value of 'DistrictName'
SO you have to pass the key name
for (var i = 0; i < len; i++) {
$('#ddlDistrict').append('<option value="' + response[i].displayFieldName+ '">' + response[i].displayFieldName+ '</option>');
}
Now from response I see displayFieldName is just a key., where as features,fieldAliases,fields are array,object & array of object again.
I am not sure if you want to target fields which have name as key and DistrictName as value. If it is o then loop condition need to be changes
for (var i = 0; i < response.fields.length; i++) {
$('#ddlDistrict').append('<option value="' + response.fields[i].displayFieldName+ '">' + response.fields[i].name+ '</option>');
}

Related

Loop a column value in a table using ajax call

I hope you are fine!
I'm new in coding so I'm facing of something without results.
I have this type of code here in JS.
key: 'generateChart2',
value: function generateChart2() {
var self = this;
var Jahr1 = [];
var years1 = "";
for (var i = 0; i < $('#mf123_select_jahr').val().length; i++) {
if (i > 0) years1 += ","
years1 += $('#mf123_select_jahr').val()[i];
}
var postedData1 = {};
postedData1.years1 = years1;
console.log(postedData1);
$.ajax({
url: "data/json.dashboard.php?call=chart2",
data: postedData1,
dataType: 'json',
type: 'POST',
success: function (dataGraph2) {
var trHTML='';
$.each(dataGraph2, function (key, value) {
for (var i in postedData1) {
Jahr1.push(postedData1[i].years1);
}
console.log(postedData1.years1);
trHTML +=
'<tr><td >' + value.Mandant +
'</td><td >' + thousandSepNeu(value.Jahr1, 2) + " €" +
'</td><td >' + value.Growth +
'</td></tr>';
});
$('#dataGraph2').append(trHTML);
}
});
}
The value.Mandant and the value.Growth are doing well. The problem that I have is that the for loop does not work. I need to thr postedData1 to choose whenever the user choose the year to show him the results.
The output of console.log(postedData1); is:
Am I making a mistake? I know that the problem is on the for loop.
Please any advice i would appreciate it.
:)

how to add options in select2 with loop and chained dropdown?

I have this code like here, I want to add <option> to each select2, when I add dynamic input.
$("#warehouse").change(function() {
var id = $("#warehouse").val();
var url = 'pipe_data.php?loc=' + id;
var idf = $("#idf").val();
var j, i;
for (j = 1; j < idf; j++) {
$("#pipe_name" + j).select2({
placeholder: '-- Choose Pipe Name --',
theme: "bootstrap",
width: '100%'
});
$("#pipe_name" + j).html('');
$("#pipe_name" + j).append('<option value="">-- Choose Pipe Name --</option>');
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: function(result) {
for (i = 0; i < result.length; i++) {
$("#pipe_name" + j).append('<option value="' + result[i].code + '">' + result[i].code + '|' + result[i].name + '|' + result[i].unit + '</option>');
}
}
})
}
});
in this code i have problem, pipe_name can't add in select2

Wikipedia API - displaying only 4 results

I'm using the Wikipedia API to display some articles. The only issue is that it only displays the first 4 results. I've looked at similar questions but still can't find a way to display more. Here's the jsfiddle.
JS:
$(document).keypress(function(e) {
if(e.which == 13) {
var searchTerm = $('#searchy').val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&format=json&callback=?";
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function(data){
//console.log(data[1][0]);
//console.log(data[2][0]);
//console.log(data[3][0]);
$('#output').html('');
for (var i = 0; i < data.length; i++) {
$('#output').prepend("<li>" + data[1][0] + "<p>" + data[2][0] + "</p></li>");
$('#centbox').css("top", "14%");
$('#resultati').css("top", "16%");
}
},
error: function(errorMessage){
alert("Error!");
}
})
};
});
You have:
for (var i = 0; i < data.length; i++) {
But data.length is always going to be 4: [0] is the search, [1] is an array of article names, [2] is an array of summaries, and [3] is an array of links.
So perhaps:
for (var i = 0; i < data[1].length; i++) {
$('#output').prepend("<li>" + data[1][i] + "<p>" + data[2][i] + "</p></li>");

javascript/php won't load data for first option in dependent dropdown

I'm having a problem with a script that is part borrowed and part my own, it is javascript and php that populates two dropdown lists, with options in the second being dependent on what the user selects in the first. For some reason, it won't load the options in the second dropdown when the initial option is selected in the first, either on page load or if it is selected manually (if the options were 'a, b, c, d, e...etc', it won't load anything for 'a').
I think it might be something to do with the javascript document ready function, but I'm afraid I know very little about javascript. This is the javascript code:
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctProxy").change();
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
Change event is only fired, when selection is changed - not when filled ;-)
Try adding $("#slctOutcome").trigger("change"); at pre-last line
Have fun :-)
Try the below. Second function wasn't being called in first function.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});

How to read this JSON response from AJAX

This is my response from AJAX call
{"screen":[{"screen_name":"SCR1","screen_id":"1"},{"screen_name":"SCR2","screen_id":"2"},{"screen_name":"SCR3","screen_id":"3"},{"screen_name":"SCR4","screen_id":"4"},{"screen_name":"SCR5","screen_id":"5"},{"screen_name":"BIGSCR","screen_id":"6"}]}
success: function(response) {
var jsondata = JSON.stringify(response);
console.log(jsondata);
var html = '';
for (var i = 0; i < jsondata.screen.length; i++) {
var screenName = jsondata.screen[i].screen_name;
var screenId = jsondata.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
}
But I keep on getting
Uncaught TypeError: Cannot read property 'length' of undefined at for loop
Try this: It Works. As smooth as silk: (See comment for explanation)
<select id="SCname"></select>
<script>
$.ajax({
dataType: 'json',
//This JSON datatype returns a json encoded response
url:"api/test.php",
//This is the URL From where you fetch the JSON Data
success: function(response){
//Since the response array object has a single array element "screen", we make it myArray
myArray = response["screen"];
console.log(myArray);
//We get six Objects in myArray.
//Thsese are Arrays of your six screens . Now Using Loops
var html = '';
for (var i = 0; i < myArray.length; i++) {
// Each element is inside DOuble Array like: myArray[0]["screen_name"]
var screenName = myArray[i]["screen_name"];
var screenId = myArray[i]["screen_id"];
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
//Check your console ouput
console.log(html);
}
});
</script>
JSON.stringify(object) returns a string. You want a JSON.parse(string) – which returns an object. Alternatively, if your response is already an object, then you don't have to parse it at all:
success: function(jsonData) {
var html = '';
for (var i = 0; i < jsonData.screen.length; i++) {
var screenName = jsonData.screen[i].screen_name;
var screenId = jsonData.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
You don't want to stringifybut to parse. Correct it must be:
var jsondata = JSON.parse(response);
But keep in mind that jQuery possibly is already parsing the JSON for you.

Categories