How to get JSON data into option list - javascript

I am getting JSON in the following format (as array of objects)
[{"0":"Ahmednagar","city_name":"Ahmednagar","1":"1","city_id":"1"},{"0":"Akola","city_name":"Akola","1":"2","city_id":"2"},{"0":"Amravati","city_name":"Amravati","1":"3","city_id":"3"},{"0":"Aurangabad","city_name":"Aurangabad","1":"4","city_id":"4"},{"0":"Beed","city_name":"Beed","1":"5","city_id":"5"},{"0":"Bhandara","city_name":"Bhandara","1":"6","city_id":"6"},{"0":"Buldhana","city_name":"Buldhana","1":"7","city_id":"7"},{"0":"Chandrapur","city_name":"Chandrapur","1":"8","city_id":"8"},{"0":"Dhule","city_name":"Dhule","1":"9","city_id":"9"},{"0":"Gadchiroli","city_name":"Gadchiroli","1":"10","city_id":"10"},{"0":"Gondia","city_name":"Gondia","1":"11","city_id":"11"},{"0":"Hingoli","city_name":"Hingoli","1":"12","city_id":"12"},{"0":"Jalgaon","city_name":"Jalgaon","1":"13","city_id":"13"},{"0":"Jalna","city_name":"Jalna","1":"14","city_id":"14"},{"0":"Kolhapur","city_name":"Kolhapur","1":"15","city_id":"15"},{"0":"Latur","city_name":"Latur","1":"16","city_id":"16"},{"0":"Mumbai City","city_name":"Mumbai City","1":"17","city_id":"17"},{"0":"Mumbai Suburban","city_name":"Mumbai Suburban","1":"18","city_id":"18"},{"0":"Nagpur","city_name":"Nagpur","1":"19","city_id":"19"},{"0":"Nanded","city_name":"Nanded","1":"20","city_id":"20"},{"0":"Nandurbar","city_name":"Nandurbar","1":"21","city_id":"21"},{"0":"Nashik","city_name":"Nashik","1":"22","city_id":"22"},{"0":"Osmanabad","city_name":"Osmanabad","1":"23","city_id":"23"},{"0":"Palghar","city_name":"Palghar","1":"36","city_id":"36"},{"0":"Parbhani","city_name":"Parbhani","1":"24","city_id":"24"},{"0":"Pune & Pimpri-Chinchwad ","city_name":"Pune & Pimpri-Chinchwad ","1":"25","city_id":"25"},{"0":"Raigad","city_name":"Raigad","1":"26","city_id":"26"},{"0":"Ratnagiri","city_name":"Ratnagiri","1":"27","city_id":"27"},{"0":"Sangli","city_name":"Sangli","1":"28","city_id":"28"},{"0":"Satara","city_name":"Satara","1":"29","city_id":"29"},{"0":"Sindhudurg","city_name":"Sindhudurg","1":"30","city_id":"30"},{"0":"Solapur","city_name":"Solapur","1":"31","city_id":"31"},{"0":"Thane","city_name":"Thane","1":"32","city_id":"32"},{"0":"Wardha","city_name":"Wardha","1":"33","city_id":"33"},{"0":"Washim","city_name":"Washim","1":"34","city_id":"34"},{"0":"Yavatmal\t","city_name":"Yavatmal\t","1":"35","city_id":"35"}]
ajax call to get json
$(document).ready(function(){
$("#select_state").change(function() {
var $state_var=$('#select_state').val();
alert("Selected State Value "+$state_var);
//make the ajax call
$.ajax({
url: 'ajax/location.php',
type:'GET',
data: {
state_name : $state_var
},
success: function(city_list) {
console.log(city_list);
var options = '';
for (var i = 0; i < city_list.length; i++) {
var city = city_list[i];
options += '<option value="' + city.city_id + '">' + city.city_name + '</option>';
}
$('#select_city').html(options);
$('#select_city').show();
}
});
});
});
Now it gives me only undefined is option list

You need to add:-
dataType;'json',
In your $.ajax code so that your response is automatically parsed and success function will execute properly.
Like below:-
$.ajax({
url: 'ajax/location.php',
type:'GET',
dataType:'json', // add this
data: {
state_name : $state_var
},.....rest code

Related

400 bad request for ajax call with GET request parameter passed to controller in spring

i'm showing a drop down list in a page based on the selection i have to show dependent drop down by passing the selected value in drop down list to the controller and return json data as response.please find below code and help me for resolving this .
Please find below ajax code
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
dataType : 'json',
contentType : "application/json",
url : "${home}getOPList",
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var operatorList;
// alert("yes");
// alert(str);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].listOfOperators);
operatorList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function(){
alert('Error while request..');
}
});
$("#opList").change(function(){
$.ajax({
type: 'GET',
dataType : 'json',
contentType : "application/json",
url : "${home}partnerDetails?operator =" +opList,
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var partnerList;
alert("yes");
alert("oplist " + opList);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].campaignName);
partnerList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].campaignName +
"</option>"
}
$('#ptList').html(partnerList);
},
error: function(){
alert('Error while request in partners..');
}
});
});
});
</script>
above is the ajax code and when the code gest executed it is directly showing " Error while request in partners.. ".in console it says it is a bad request with 400 response code for the below url.
http://localhost/Promotions/partnerDetails
please suggest on this

How to save the data into database in jquery and display upon the screen using web api

I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.

how to clean option values under select - html tag

I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});

Populate Dropdown List based on Autocomplete Value

I have three form fields for country(text input), city(text input) and street(dropdown):
country is autocomplete
city is auto-filled based on the result of country
street I want to generate dropdown list based on selected city
Here is my current JavaScript script:
$(".country").autocomplete("get_city.php",{ mustMatch:true })
.result(function (evt, data, formatted) {
$(".city").val(data[1]);
});
So far it's auto-filling the city(text input).
My problem now is to generate drop down list based on the filled city.
I Think you need somthing like this:
$(".country").change(function () {
var webMethod = "filewithdata.php";
var parameters = { id: $('.country').val() };
$.ajax({
type: "GET",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//console.log(response);
json_obj = $.parseJSON(response);
var output = '';
for (var i in json_obj) {
if (json_obj[i][4] == 1) {
output += '<option value="' + json_obj[i][0] + '">' + json_obj[i][0] + '</option>'
}
}
$('#dropdownElement').empty().append(output);
},
error: function (e) {
$(divToBeWorkedOn).html("Unavailable");
alert("Errror:" + e);
}
});
});

Populate dropdown with json data

I am trying to populate a dropdownbox with data from a JSON page.
Here is the code I am using:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data
});
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
});
</script>
And here is what the json data returns:
{"d":"{\"16\":\"hello\",\"17\":\"world\"}"}
I am getting an error that "data is undefined." Do I have to somehow tell JQ how to read the json data?
Firstly, the data variable you are passing to the ajax call is not defined (well, not in the code sample you provided), and secondly the ajax call is happening asynchornously, so you need to do something with the returned data, i.e. via a success callback. Example:
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
also you shouldn't need to parse the data returned from the ajax call, as jQuery will automatically parse the JSON for you, ( should need the $.parseJSON(data.msg))
EDIT
Based on the interesting format of the JSON, and assuming that it cannot be changed, this should work (ugly though)
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
data = data.d.replace(/{/g, '').replace(/}/g, '').split(',');
var obj = [];
for (var i = 0; i < data.length; i++) {
obj[i] = {
value: data[i].split(':')[0].replace(/"/g, '').replace('\\', ''),
label: data[i].split(':')[1].replace(/"/g, '')
};
}
var htmlToAppend = "";
for (var j = 0; j < obj.length; j++) {
htmlToAppend += '<option value="' +
obj[j].value +
'">' + obj[j].label +
'</option>';
}
$('#taxList').append(htmlToAppend);
}
});
});
You need to use the success option to return the data.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
success: function(data){
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
</script>

Categories