I am developing MVC application.
I am trying to pass the data from controller and trying to display using JQuery.
I create the array into Controller and pass it to Jquery using Json.
here is the array...
and here is the code of JQuery.
function getProductDetails(productCode, Index) {
$.ajax({
url: "/Product/getProductDetails/",
data: { Id: productCode },
dataType: "json",
success: function (result)
{
$.each(result.StockData, function (key, Value) {
alert(key + "+" + Value);
});
}
});
}
I have displayed the alert for the values...
it shows as below... Key shown perfectly but value shows as a object.
Try to stringify that object,
$.each(result.StockData, function (key, Value) {
alert(key + "+" + JSON.stringify(Value));
});
According to your new request try like,
$.each(result.StockData, function (key, Value) {
alert(key + "+" + (Value.Value));
});
Related
I have a Json object as following.
{
"firstName":"John",
"lastName":"Doe"
"123":"456"
}
I want to access they keys and value. After reaching, I will set them into fields. But I don’t why it doesn’t work. I’ve checked its syntax has no problem.
What I’ve tried,
$(document).ready(function f() {
$.ajax('http://soner.dev/test.txt', {
success: function(data, status, xhr) {
$(data).each(function(i,val)
{
$.each(val,function(key,val)
{
console.log(key + " : " + val);
alert(key + " : " + val);
$('#{key}').val(val);
});
});
setTimeout(f, 1000); // refresh the data at each second(data changes at each 1sec)
}
});
});
By the way, $('#{key}').val(val); in which I try to use Template Literals.
You've got an object there, not an array. In JSON, objects are wrapped with { and } and have named properties like "firstName" etc. Arrays are wrapped with [ and ] and have numbered indexes like 0, 1, 2 etc.
Consequently you can make your looping a lot simpler and just iterate over the object keys directly.
N.B. You also need to parse the data from JSON (i.e. a notation format in plain text) into a JavaScript variable before you can begin. Since you're using jQuery's $.ajax() you can set the dataType: "json" option which causes jQuery to process the response as JSON and parse it for you automatically before it provides the data to your callback.
I also fixed your template literal syntax - you need to use backticks (`) and the dollar sign to make it work.
Here's a runnable demo (using a dummy endpoint since yours doesn't support CORS):
$(document).ready(function f() {
$.ajax({
url: "https://api.myjson.com/bins/ntsyj",
dataType: "json"
}).done(function(data) {
$.each(data, function(key, val) {
console.log(key + " : " + val);
$(`#${key}`).val(val);
});
//setTimeout(f, 1000); // refresh the data at each second(data changes at each 1sec)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="firstName" />
<input id="lastName" />
<input id="123" />
The response is a plain string so yo. firstly, you need to parse it using build-in JSON.parse() function and then you can iterate over it.
To use template literal, you should put your variable between ${ and }.
Please consider the code bellow:
$(document).ready(function f() {
$.ajax('http://soner.dev/test.txt', {
success: function(data, status, xhr) {
var parsedData = JSON.parse(data);
$.each(parsedData, function( key, val ) {
console.log(key + " : " + val);
alert(key + " : " + val);
$(`#${key}`).val(val);
});
setTimeout(f, 1000); // refresh the data at each second(data changes at each 1sec)
}
});
});
While retrieving JSON array data using $.each method, I am able to get the array values, but apart from that it's showing 'NaN' values and showing the below error.
"Uncaught TypeError: Cannot use 'in' operator to search for '5' in Hello!"
Seems it's looping through all the objects not only array, if this is the case how can I get only array values and how can I get all the values(including and excluding array values).
one more query does this rawgit works for only method 'GET', because while using method 'POST' throwing error(403 (Forbidden)).
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
$.each(data, function(index, obj){
$.each(obj, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
JSON:
{
"items": [
{
"key": "First",
"value": 100
},{
"key": "Second",
"value": 200
},{
"key": "Last",
"value": "Mixed"
}
],
"obj": {
"number": 1.2345e-6,
"enabled": true
},
"message": "Hello!"
}
It sounds like you only want to iterate data.items but you're iterating over everything. Try this:
$.each(data.items, function(index, obj) {
$('#show-data').append(obj.key + obj.value + '<br/>');
});
https://jsfiddle.net/rrsku4Lq/
The problem is when the second loop reaches "message": "Hello!", that is not a object to be looped again, so for that element only the first loop is needed.
To correct, just make an if statement to enter the second loop only in case obj is an Object.
I also changed the nested loop index name to index2.
$.each(data, function(index, obj){
// Only do nested loop if obj is Object
if (obj instanceof Object) {
$.each(obj, function(index2, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
}
});
If you're only interested in data.items, than you can use
$.each(data.items, function(index2, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
You have an unnecessary for loop. The response is one JSON object in your case. You simply need to iterate the data items. UPDATE: How you handle a response depends on what you want to accomplish. In practice, you'll generally know how to access the data you need from the response, but as others have suggested, you can iterate through the keys in the response object and check for types
var object = {
arr : [1,2,3],
nestedObject : { }
};
for (var key in object) {
console.log(key);
console.log('Is array? ' + Array.isArray(object[key]));
// Now you can handle the data based on it's type...
}
In this case, you could choose to expect the response to include a items key and iterate over that. (It's also good practice to validate that you can process the response)
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function(data) {
// data is your JSON object.
data.items.forEach(function(item) {
$('#show-data').append(item.key + item.value + '<br/>');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show-data"></div>
Also, 403 indicates that the resource is blocked for the current user. Verify that your POST method is publicly accessible and that you are authorized to make the request.
You should parse the json first. And as #Jason P said, iterate data.items
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
var parsedData = $.parseJSON(data);
$.each(parsedData.items, function(index, obj){
$.each(obj, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
You are looping through all the elements in the array. I think you need to loop through only 'items' element as only that element contains the 'key' and 'value' elements.
Even though you are doing that, you can check if the key and value element exists, and if it does, do whatever your code wants.
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data)
{
$.each(data, function(index, obj)
{
$.each(obj, function(index, element)
{
if(element.hasProperty('key') && element.hasProperty('value'))
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
console.log(data.items);
$.each(data.items, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
}
});
I'm trying to pull in some json data using ajax. I am able to successfully pull data from the first 2 items but its the data under "placemark" that I really need. I need to be able to display this in a list much like an rssfeed. I'm not sure how to drill down deeper into the json to pull the data I need. any help greatly appreciated.
$.ajax({
type: 'GET',
url: rssAPI,
success: function(data){
console.log(data);
$.each(data, function(index, item) {
$.each(item, function(key, value) {
$('.listing').append(key + ': ' + value + '</br>');
});
});
}
});
here's what my json looks like
and this is my output
You need to either output, if the property value is a string, or iterate further (i.e. another loop) if it's an array, as is the case with the Placemark properties.
So:
$.each(data, function(index, item) {
$.each(item, function(key, value) {
if (typeof value != 'object')
$('.listing').append(key + ': ' + value + '</br>');
else
$.each(value, function(key, value) {
//these are your items under Placemark
});
});
});
Here placemark contains array of json objects. So you need to access it as below :
for(i=0; i<Document.Placemark; i++){
console.log(Document.Placemark[i].name);
console.log(Document.Placemark[i].description);
}
I have de next objet jSon:
{"prtg-version":"14.3.10.2422","treesize":3700,"":[{"objid":0,"probe":"","probe_raw":""}]}
I need the parametres to objid and prove and the next programm javascript:
$(document).ready(function()
{
/* call the php that has the php array which is json_encoded */
function act()
{
$.getJSON('https://10.213.8.25/api/table.json?columns=objid', function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.objid +' </li>');
});
});
});
}
setInterval(act, 1000);
});
if modifique my jSon all ok:
[{"objid":0,"probe":"","probe_raw":""}]
but the URL works with the before jSon and my programm javascrip and does not work can you help me to comment on the error?
Thank!
Given the following JSON:
{
"prtg-version":"14.3.10.2422",
"treesize":3700,
"":[{"objid":0,"probe":"","probe_raw":""}]
}
... I would first point out that it's highly unusual to have an empty string ("") as a JSON key. That being said, you can do that if you want. If you want to iterate over those values, though, you need to replace:
$.each(data, function(key, val) {
... with this:
$.each(data[""], function(key, val) {
I still have problems, I have armed the JSON object in PHP and call control and it works but by changing the URL address where you should get your information does not throw me anything you know if I make any changes?
$(document).ready(function()
{
/* call the php that has the php array which is json_encoded */
function act()
{
$.getJSON("https://10.213.8.25/api/table.json?&content=sensors&output=json&columns=objid&count=1&username=prtgadmin&password=SIEoperaciones01", function(data) {
//$.getJSON('DMS_PRTG_prueba.php', function(data) { ***OK***
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.objid +' </li>');
});
});
}
setInterval(act, 1000);
});
{"prtg-version":"14.3.10.2422","treesize":3188,"sensors":[{"objid":1001}]}
I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}