Jquery, For each looping a List of objects - javascript

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)
});

Related

Access an item of the loop out of the loop

So i have a couple of item that iterate through from database using Jquery and for each of them I output a button to select that specific item and when I click on that row's button I want to POST the details to the controller in MVC.
$.each(data, function (i, val) {
var item = $('<div></div>');
item.append('<h2><a>' +val.Name+ '</a></h2>');
item.append('<a id="button">SELECT</a>');
tab.append(item);
});
And I have this function for the button:
$('#myId').on('click', 'a#button', function () {
alert('Name'+val.Name+'');
var item = { Name: val.Name };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{item:" + JSON.stringify(item) + "}",
url: "/Person/GetData"
});
});
If I add the function inside the loop it will iterate as many times as there are items in there. So how can I deal with this in order to send post the name after I press SELECT button?
Use DOM traversal method to get the desired element to extract text to be passed to $.ajax()
As Identifiers in HTML must be unique use CSS class selector to target them
$.each(data, function (i, val) {
var item = $('<div></div>');
item.append('<h2><a>' + val.Name + '</a></h2>');
item.append('<a class="button">SELECT</a>');
tab.append(item);
});
In the event handler, use .prev() to target the sibling <H2> element
$('#myId').on('click', 'a.button', function () {
var item = {
Name: $(this).prev('h2').find('a').text()
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
item: item
},
url: '#Url.Action("GetData", "Person")' //Note: this will not work in separate JS file
});
});
Move the click to the bottom of the page outside any loop,
change the id to a class item.append('<a class="button">SELECT</a>'); for your click event to select the proper value
$('#myId').on('click', 'a.button', function () {
var val = $(this).prev('h2 a').text();//get the val.Name value
var item = { Name: val};//create a object
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: item,//jquery will take care of the encoding
url: "/Person/GetData"
});
});

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>");
}

Get the value of input tag for Ajax Request

<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/

How to populate data from API and load into dropdown

I am working on MVC application that uses API and i want to call a method from the API so that it will load the data to the combo-box. I have no idea on how i can tackle this as am new this.
Thanks.
ClaimController function from the API which got this function.
[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
try
{
using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
{
Request.Headers.Clear();
var tmpresults = logic.GetScheme();
var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
}
}
Views from the Client which is the UI
I want to call that function from API to load the data into the combo-box
function GetAllScheme() {
var select = $("#ddlScheme");
$.ajax({
type: "GET",
url: "http://localhost:55393/_Api/Claim",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
var serverResponse = datavalue;
contentType: "application/json";
$.each(serverResponse, function (i, serverResponse)
{
select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Dropdown
<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
<select
</select>
</div>
You have to append option elements into your select (dropdown) element after you get the server response. Something like this:
function GetAllScheme() {
// get the dropwdown by its id
var select = $("#ddlScheme");
$.ajax({
...
success: function (data) {
$.each(myJsonObject, function (i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description + '</td></tr>');
// for each element, add an option into the dropdown
select.append('<option>"+ mobj.Description +"</option>')
}
});
...
)}
See jsfiddle https://jsfiddle.net/n4mtj9om/
If use Chrome enter in developers tools a see how response the server put a breakpoint after server response because when use maybe
put this
function GetAllScheme() {
$.ajax({
type: "GET",
url: "http://localhost:32359/api/Claim",
dataType: "json",
success: function(data) {
$.each(data.responseJSON, function(i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description +
'</td></tr>');
});
},
error: function(xhr) {
alert(xhr.responseText);
}
});
}

Binding json string with drop-down using jquery

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

Categories