Binding json string with drop-down using jquery - javascript

I am new to jQuery. I am creating the json string in my servlet using gson-2.2.3.jar:
Gson gs = new Gson();
String json = gs.toJson(names);
System.out.println(json);
PrintWriter out = resp.getWriter();
out.println(json);
out.close();
Below are the two commented codes I tried for binding the json string with drop-down but none of them works:
$.ajax({
type:"POST",
url: "DropDownController",
success: function(result){
alert(result);
/* for (var id in result) {
$("#drpDown").append('<option value="'+id+'">'+id+'</option>');
} */
/* $.each(result, function (index, value) {
$("#drpDown").append('<option value="'+value.id+'">'+value.name+'</option>');
}); */
}
});
The alert message box present in the success displays the json string in below format:
["Alabama","California","Alaska","Ohio"]
Kindly let me know how to bind the above json string data with the drop-down.

Try like this:
$.ajax({
type: 'POST',
url: 'DropDownController',
dataType: 'json',
success: function(result) {
$.each(result, function() {
$("#drpDown").append(
$('<option/>', {
value: this,
html: this
})
);
});
}
});

Try this
var jso=["Alabama","California","Alaska","Ohio"]
for (var i in jso) {
$("#test").append('<option value="'+jso[i]+'">'+jso[i]+'</option>');
}
DEMO

Related

Posting the checkbox value using hardcoded string value using serialize() works but not working while using value.toString() in ajax

Trying to post the checkbox data using serialize() in ajax. The data is in object format and converted to string data using value.toString() and passed as parameter to api but the api didn't work. When used a hardcoded data instead it worked!
I am trying to post the checkbox data to the backend using serialize() but the function never starts nor the data is being send to the backend. I have used value.Join(","), still it does not work.
The code:
$(document).on("click", ".update", function() {
var ID = $(this).attr("ID");
if (confirm("Update")) {
$('#update').modal('show');
} else {
return false;
}
$('#update_form').on("submit", function() {
var update = [];
$.each($("input[name='Ucheckbox[]']:checked"), function() {
update.push($(this).val());
});
var un = update.join(",");
$.ajax({
url: "url/api",
method: "POST",
data: $('#update_form').serialize() + "&id=" + id + "&un=" + un,
success: function(data) {
alert(data);
},
error: function(res) {
alert('Error');
}
});
});
});
But when assigned a hardcoded string value in un variable the redirection to backend works and the values are received at the backend.
$(document).on("click", ".update", function() {
var ID = $(this).attr("ID");
var un = "1,2,3"
$.ajax({
url: "url/api",
method: "POST",
data: $('#update_form').serialize() + "&id=" + id + "&un=" + un,
success: function(data) {
alert(data);
},
error: function(res) {
alert('Error');
}
});
});
});
I want the data to be converted to string and passed as parameter to backend.

jquery add value and text to li of ul elements from json reponse

We want to bind json response to li elements with each element having value as id and text as name.
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function(response) {
var items = [];
$.each(response, function(i, item) {
items.push('<li</li>",{value:item.id,text:item.name}');
});
$('#formFieldCity ul').append(items.join(''));
}
});
But no success, I don't see any binding. Can anyone help?
you should write like this:
$.each(data, function(i, item) {
items.push('<li id="'+item.id+'">'+item.name+'</li>');
});
I think you mean
var list = $('#formFieldCity ul'); //caching
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function (response) {
var items = [];
//Misplaced variable here: data instead of response
$.each(response, function(i, item) {
var mapped = {value:item.id,text:item.name};
items.push(mapped)
list.append("<li id=\""+item.id+"\">"+item.name+"</li>");
});
}
});
This will basically print a json in your HTML.
Hope I got what you wanted.
EDIT:
If your response is an array, consider using a simple for loop, which is about 8x faster then the jQuery.each
for(var i=0; i<response.length; i++){
var mapped = {value:response[i].id,text:response[i].name};
items.push(mapped)
list.append("<li id=\""+mapped.value+"\">"+mapped.text+"</li>");
}

How to find all the children for its parent in Jquery?

I'm using Codeigniter and Jquery with AJAX method to query data from two tables in my database with select join from table group with table cat.
This is table description
Table1: cat
======c_id======fk_group_id====cat_name===
======1========1==============cat1=======
======2========1==============cat2=======
======3========1==============cat3=======
======4========1==============cat4=======
Table2: cat_group.
======gid=======gname====gstat============
======1========1=========1==============
======2========1=========1==============
======3========1=========1==============
======4========1=========1==============
Here is my Model:
This function will selct from table cat_group join with table Cat on gid = cat.fk_group_id.
public function cat(){
$this->db->select('cat_group.*, cat.*');
$this->db->from('cat_group');
$this->db->join('cat', 'cat.fk_group_id = cat_group.gid','all')->where('cat_group.gstatus = 1');
return $this->db->get()->result();
}
My function in Controller:
I call method cat from Model and echo data as Json_encode to the client browsers
public function select_cat_by_group(){
$this->load->model("main/slide_cat_m");
$val = $this->slide_cat_m->cat();
if(!$val){
return false;
}else{
echo json_encode($val);
}
}
Jquery Ajax
$.ajax({
method: "GET",
url: '<?PHP echo base_url('main/select_cat_by_group');?>',
dataType: "Json",
success: function (data) {
$.each(data, function (i, val) {
if(val.fk_group_id = gid){
//I want to select all the rows in table cat where fk_groupd_id = gid of table cat_group but I can't
}
});
}
})
My Json
[{"gid":"1","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"1","fk_group_id":"1","cat_name":"fuck1","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"5","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"2","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"6","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"7","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"8","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"9","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"10","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"15","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"16","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"17","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"18","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"19","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"20","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"21","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"22","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"23","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"24","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"25","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"26","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"}]
You did small mistake in model. However it should be:
$this->db->select('cat_group.*, cat.*');
$this->db->from('cat');
$this->db->join('cat_group', 'cat.fk_group_id = cat_group.gid','all')->where('cat_group.gstatus = 1');
return $this->db->get()->result();
It must return all the rows of cat where fk_groupd_id = gid. Now you should parse the json result.
UPDATE:
$.ajax({
type: "POST",
url: 'YOUR_URL',
dataType:'JSON',
success: function(data) {
$.each(data, function(index, element) {
//console.log(index);
//alert(element.c_id);
console.log(element.c_id);
console.log(element.cat_name); // here console.log() is used to debug the data.
});
}
})
It's up to you now how you will display the data in HTML. You can check this example as how to parse json object and display them into DOM: how to parse json data with jquery / javascript?

Jquery, For each looping a List of objects

I have a list of "User" with has Name, Surname and Email.
I need to loop through it on Jquery. This list is returned by a server side method
success: function (result) {
// var res = result.d
$.each(result, function (index, obj) {
alert(obj);
});
}
Does anyone know how it can be done?
Edit: The entire Ajax list:
var param = '{"NameofMap":"' + nofm + '", "VillNum":"' + numberV + '"}';
$.ajax({
url: 'GenerateMap.aspx/AddVill',
type: "POST",
data: param,
dataType: "json",
contentType: "application/json",
error: function (msg)
{ alert("Fails"); },
success: function (result) {
$.each(result, function (index) {
alert("Test");
});
}
});
This is the entire Ajax. It returns a list of Class instances ("User")
It displays "Test" but if I change that with alert(result[index].Name); , it displays just an empty box.
As you haven't provide proper information, still you can give this a try.
If you're getting into the success: and able to get alert, you can try like this:
You can have properties with it's name
--> result.Name
--> result.Surname
--> result.email
So Your code will be like following:
$.each(result, function(index) {
alert(result[index].Name);
.......
});
Or
$.each(result, function(index, item) {
alert(item.Name);
.......
});
This might help!
try
$.each(data,function(i, item){
alert(item.name)
});

Trying to convert json to xml but shows error

I'm trying to convert the json result into xml type. However, it doesn't seems to work. Couldn't find out what's wrong. Please help.
The code is:
<script src="../Jquery Autocomplete/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Jquery Autocomplete/jquery.json-2.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$(".openModalLink").click(function()
{
var start=$(this).parent().parent().find(".start").val();
var end =$(this).parent().find(".end").val();
$.ajax(
{
type: "POST",
url: "frmCollegeExamScheduleMst.aspx/ServerSideMethod",
data: "{'paraml': '" + start + "','param2': '" + end + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success:function(result)
{
var xmlDoc = $.parseXML(result);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var data = new Array();
var i =0;
$.each(customers, function ()
{
//do something
});
},
error: function(err) {
alert('Error:' + err.responseText + ' Status: ' + err.status);
}
});
});
});
When you specify dataType: "json" the response is converted to a JSON object and does not remain a string.
Try removing the parameter.
Try like this:
success: function(result) {
var xmlDoc = $.parseXML(result.d);
...
}
Notice the result.d. I guess your ASP.NET PageMethod looks like this:
[WebMethod]
public static string ServerSideMethod(string param1, string param2)
{
DataSet ds = ...
return ds.GetXml();
}
This string is JSON serialized. In order to retrieve it on the client the ASP.NET infrastructure adds the d parameter:
{"d":"some xml here"}
Another thing that you should absolutely change in your code is replace:
data: "{'paraml': '" + start + "','param2': '" + end + "'}"
with:
data: JSON.stringify({ param1: start, param2: end })
to ensure that your request parameters are properly JSON encoded. Think for example what will happen if start = 'foo\'bar'. You will end up with:
data: {param1: 'foo'bar', param2: 'baz'}
which as you can see completely breaks your JSON.
If the response from your AJAX request is xml then you should set it accordingly.
$.ajax({
data: {paraml: start, param2: end},
dataType: "xml",
success:function(result) {
var $xml = $(result);
}
});
No need for contentType nor concatenating in data.

Categories