How to display json feed to user? - json

I have a valid json feed that I am pulling from the server by accessing a php file using jquery. An example of the json feed returned from querying the php file is
{"items":[{"acc_number":"11111","acc_name":"TestAccount","demographics":["Some
Street","SomeState","99999"],"last_thirty":null,"phone":null,"sms":null,"email":null}, {"acc_number":"22222","acc_name":"MyAccount","demographics":"MyStreet","MyState","99999"],"last_thirty":null,"phone":null,"sms":null,"email":null}],"total_items":"80","md5sum":"c7a834d45bdf348abfdcdb95994c7608"}
I am using the code below which I though would go through feed and bring down all of the records and fields that were not NULL. But I am not getting anything.
$.ajax({
type= 'GET',
url: 'http://MyURL.com',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var items = [];
$.each(data, function(key,val) {
items.push('<li id="' = key = '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
});
}
Any help/tips is appreciated as always.
Thanks!
Updated based on answers below.
$(document).ready(function() {
testNews();
});
function testNews() {
$('body').append('<h1>News</h1>');
$('body').append('<h2>Main Display</h2>');
$('body').append("<div id='success_news_main' class='waiting'>Waiting for response</div>");
$.ajax({
type: "GET",
url: 'http://MyURL.com/news.php',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var ul = $('<ul/>').addClass('my-new-list').appendTo('body');
$.each(data.items, function(k,v) {
$('<li/>').attr('id', k).html(v).appendTo(ul);
});
}
});
}

Try iterating over data.items and not over data as this is your collection:
success: function(data) {
var items = [];
$.each(data.items, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
...
}
Also your items.push method seems broken with those multiple = characters. You probably meant +.
Another remark is the val variable inside the $.each statement. It will be an object. You probably want to select a specific property from this object, like:
items.push('<li id="' + key + '">' + val.acc_number + '</li>');
And the key will be the index of the array. And because ids in HTML cannot start with a number if you want to have valid HTML you might need to prefix your li id:
items.push('<li id="item_' + key + '">' + val.acc_number + '</li>');

You shouldn't use string concatenation when forming the html tags for display. Instead use jQuery's functions create the dom elements, add attribute values to them and add them to the page.
Here's a suggestion on modifying your code:
$.ajax({
type= 'GET',
url: 'http://MyURL.com',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var ul = $('<ul/>').addClass('my-new-list').appendTo('body');
$.each(data.items, function(k,v) {
$('<li/>').attr('id', k).html(v).appendTo(ul);
});
}
});
This is also easier to read and doesn't look through the array twice.
Also, the "v" variable within "$.each" will be the objects of the array within the json. You'll need to access their individual properties and create the necessary html/elements within the li instead of setting it directly as the html property.

Iterate over the data.items since the JSON returns the values in that array. This code example also fixes "=" where "+" should have been.
$.ajax({
type= 'GET',
url: 'http://MyURL.com',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var items = [];
$.each(data, function(key,val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
});

Related

How can I load data from controller (JSON) to a ListBox in View?

I am new in ASP.NET Core. I just want to simply load a JSON file's data into a listbox.
Here is the controller class:
public class EmployeeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetEmpList()
{
var empList = new List<Employee>()
{
new Employee { Id=1, Name="Manas"},
new Employee { Id=2, Name="Tester"}
};
return Json(empList);
}
}
And here is the view:
<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
type: "GET",
url: "/EmployeeController/GetEmpList",
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++) {
ddlEmployees.append('<option> ' + data[i] + '</option >');
}
}
}); </script>
Assuming that you are successfully able to make requests to your API endpoint I think the part that needs to be updated is actually your jQuery in the view. Since you're returning a list as JSON, what you'll have in your data argument is an array of objects. So in order to populate the values of the <option> tag with the values in your JSON object, you'll need to access the JSON fields that you define in your Controller.
<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
type: "GET",
url: "/EmployeeController/GetEmpList",
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++) {
ddlEmployees.append('<option value="' + data[i].Id + '"> ' + data[i].Name + '</option >');
}
}
}); </script>
The naming convention for response json in asp.net core is camel case instead of pascal case.
You could add console.log(data) to check the response in Console panel(press F12 in browser). Then you will find the property name in response is camel case.
Change like below:
$.ajax({
type: "GET",
url: "/Employee/GetEmpList", //it should be Employee/xxx instead of EmployeeController/xxx
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++){
ddlEmployees.append('<option value="' + data[i].id + '"> ' + data[i].name + '</option >');
}
}
});

Knockout applyBindings does not applyBinding

I have just started to use knockout.js and am stuck when trying to show JSON data.
My HTML is
<p>Dealer Location: <input id="dealerlocation" data-bind="value: DealerLocation" /></p>
<p>Contact Report Date: <input id="crdate" data-bind="value: CRDate" /></p>
My Script Block is
function viewAction() {
var self = this;
self.DealerLocation = ko.observable("");
self.CRDate = ko.observable("");
};
var viewActionModel = new viewAction();
function GetActionByID() {
$.ajax({
type: "POST",
url: "/ws/someservice.asmx/GetAction",
data: "{pacid: '" + $('input[id$=hidActionID]').val() + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
var action = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$.each(action, function (index, axn) {
viewActionModel.DealerLocation = axn.DealerLocation;
viewActionModel.CRDate = axn.CRDate;
});
}
});
}
$(document).ready(function () {
GetActionByID();
//alert(viewActionModel.DealerLocation);
ko.applyBindings(viewActionModel);
});
Note: If I uncomment alert then applyBinding works otherwise it does not.
What is missing here???
Ragards.
This is a wrong way to assign observables.
viewActionModel.DealerLocation = axn.DealerLocation;
viewActionModel.CRDate = axn.CRDate;
Do it like this.
viewActionModel.DealerLocation(axn.DealerLocation);
viewActionModel.CRDate(axn.CRDate);
By doing what you do now you are replacing observables with regular variable. It was working with alert because this replacement took place before binding and knockout just picked up your regular variables. Read more about observables.

Trouble to fetch data from JSON

Am working in jQuery Mobile and PhoneGap.
Currently I have a Trouble to fetch data from JSON.
My JSON format is ;
{
payment: {
1: "Visa",
2: "American Express",
3: "Mastercard/Eurocard",
4: "Visa – Verified by Visa",
5: "Mastercard/Eurocard – Securecode"
}
}
And Its XML will looks like this ;
<payment>
<1>Visa</1>
<2>American Express</2>
<3>Mastercard/Eurocard</3>
<4>Visa – Verified by Visa</4>
<5>Mastercard/Eurocard – Securecode</5>
</payment>
I want to fetch the details in to a selectbox.
and My Code is ;
function loadpayment() {
$.ajax({
url: 'https://www.sample.net/json/jsn_payments.php?json=1&rcg_mobile=2',
data: '',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain: true,
cache: false,
async: false,
success: function (data, textStatus, jqXHR) {
var count = data.payment.length;
var card_type_ = $('#card_type_');
var card_type = '';
card_type_.empty();
card_type += '<option selected="selected" value="">' + BookCar2_Cardtype_label + '</option>';
for (i = 1; i < count; i++) {
card_type += '<option value=' + data.payment.[i] + '>' + data.payment.[i] + '</option>';
alert(data.payment.payment[i]);
alert(0);
}
card_type_.append(card_type);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + "-" + errorThrown);
}
});
}
But Its not working !!! I thinks its a simple mistake but i lost lot of time to solve this issue.. so please help me :(
when you use the json as in the question you cannot access them as property beacuse it is a number remember you cannot define number variable. or cannot access it like array as it is an object.
but it s and object with key so you should be able to acces them like below
obj["1"], obj["2"] etc
in your case try data.payment[i] or just in case data.payment[i.toString()]
also just notices you are using for loop as it s an array but it not so data.payment.length returns undefined. you should use foreach loop for payment, try below code.
for (var key in data.payment)
{
card_type += '<option value=' + data.payment[key] + '>' + data.payment[key] + '</option>';
alert(data.payment[key]);
alert(0);
}
Instead of using a for loop, use $.each()
$.each(data.payment,function(key,option)
{
card_type_.append('<option value="'+key+'">'+option+'</option>');
});
Other than that, I would say data.payment.[i] should be data.payment[i]
*and as cfs pointed out the missing quotes for value=""
I'm not exactly what error you're seeing, but I can see that the HTML you are creating is not valid: you're missing quotes around the value attribute in your option elements.
EDIT You are also accessing your arrays incorrectly. You don't need a dot between the data.payment and the [i]
Try this instead:
card_type += '<option value="' + data.payment[i] + '">' + data.payment[i] + '</option>';
I have put your JSON code inside a JSONLinter and it seems your JSON code is invalid.
You should use this code instead:
{
"payment": [
"Visa",
"American Express",
"Mastercard/Eurocard",
"Visa – Verified by Visa",
"Mastercard/Eurocard – Securecode"
]
}
You can also use $.each instead of the "for".
Finally I got the Solution :-)
And My code is :
function loadpayment(){
$.ajax({
url: 'https://www.sample.net/json/jsn_payments.php?json=1&rcg_mobile=2',
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success: function(data, textStatus, jqXHR){
var count = data.payment.length;
//alert(count);
var card_type_=$('#card_type_');
var card_type = '';
card_type_.empty();
card_type +='<option selected="selected" value="">'+BookCar2_Cardtype_label+'</option>';
for (var key in data.payment)
{
card_type += '<option value=' + data.payment[key] + '>' + data.payment[key] + '</option>';
}
card_type_.append(card_type);
},
error: function(XMLHttpRequest, textStatus, errorThrown){alert(textStatus +"-"+ errorThrown);}
});
}
Thank you.. # Onur TOPAL!!

Unable to recieve JSON from Webmethod using $.getJSON or Ajax call

I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help

Read Json Value using Ajax/Jquery

I want to read and assign value to a DIV as it is printed on this web service http://abc.com/new2/app/android/get_product_size.php?productID=113
For example get_product_size.php page may return Text or Number.
I have used following code for the same, the problem is its returning 0 Value when i do an alert.. my code is as follows
<div class="home%%GLOBAL_ProductId%%"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var productsize = $('.siz').val();
var id =%%GLOBAL_ProductId%%;
var AllData="" ;
var html="";
//alert(id);
$.ajax({
type: "POST",
url: "http://abc.com/new2/app/android/get_product_size.php?productID="+id,
data: "{Size:'" + productsize + "'}",
//data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: true,
success: function(msg) {
AjaxSucceeded(msg);
AllData = html.fromhtml(data.d);
$("#home%%GLOBAL_ProductId%%").html(AllData);
//42.toFixed(2);
},
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
});
</script>
AllData = html.fromhtml(data.d);
What is this "data" in your success function ? The success function's signature is
"success(data, textStatus, jqXHR)" ... Try using this one.
Also, you don't have to provide a stringified map like this
data: "{Size:'" + productsize + "'}"
You can just say {"Size" : productSize}.
at this point in your ajax block:
data: "{Size:'" + productsize + "'}",
you should remove the quotes surrounding productSize, like this:
data: "{Size:" + productsize + "}",
whatever value you put on the other side of that colon will be the value that gets returned when you call data.Size