Json returns the object as undefined - javascript

The similar questions didnt work for me. I have a AJAX GET request. When I show the entire json in the console log it works, but I cant select a single object from it.
My JS
$.ajax({
type: "GET",
url: "http://localhost:8092/api/getdata",
dataType: "json",
success: function (data) {
console.log(data["date"]);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
This code returns undefined but if I only use console.log(data) it shows everything. Not sure what to do from here.
This is the output when I use console.log(data)
{
"date": "04-06-2020",
"id": 4
}
SS when I use console.log(data)
SS when I use console.log(data["id"])

It seems you didn't show us the complete output of console.log(data) in your question, there are square brackets ([ ]) missing around it! According to your console screenshot, you get an array, with one object in it.
So the structure is:
[
{
"date": "04-06-2020",
"id": 4
}
]
Therefore, you need to access the first array element (using [0]) to get the object itself, and from there the property date, like this:
console.log(data[0].date)
(Of course, data[0]["date"] works too, but in my opinion the dot-based property access looks cleaner.)

data["date"] is used for object which has date attribute. But in your response is an array
you need to say data[0]["date"] or data[0].date

Related

Extract JSON response from jquery ajax to html div

I could not retrieve data to jquery div element but i can see ajax response in firebug.
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})
this is my response.for example my url contains data productCount:64 ,I should extract productCount from ajax success and display it in html div id result
When you parse out the JSOn data you use it like so:
var parsed_data = JSON.parse(JSON_DATA);
$('#result').html(parsed_data.key);
So if your parsed_data is somewhat like:
{name:"test",age:12}
then you use it like:
$('#result').html(parsed_data.name); //it will give you test
if you really want to print out the whole data use JSON.stringify(obj) like so:
$('#result').html(JSON.stringify(parsed_data));
In your code you are returning a json and you are trying to insert ino the div it, into the div you can only insert html code instead json.
Try to inspect the json you are returning and in case you need to insert each element into the div, do it, but don't do for all.
The html() method doesn't know what you want to assign, it only insert an html.
You need to iterate over your json data in returnData. You are not able to put json directy into html. You need to convert / parse / iterate it before. So, for example:
$.each(returnedData, function (index, value) {
// do stuff with it, e. g.:
// $('#result').html($('#result').html() + value);
});
https://jsfiddle.net/m8udusps/
The code here actually works. However it says there is a problem when it is parsing the JSON. You needed to add crossDomain: true, to allow it to actually get the results.
Having received a supposed JSON struct like:
{
"Field1": "value1",
"Field2": "value2"
}
This code gets the values of the keys (just first key in this example). Result is an alert message with Data: value1:
$.ajax({
'url' : './localurl',
'type' : 'GET',
'success' : function(data) {
alert("Data: "+data.Field1);
},
'error' : function(request,error) {
alert("Error in response: "+JSON.stringify(data));
}
});
In this case Field1 is the key received and it is directly accesible through data variable, so it is not necessary to do the JSON.parse(data) (in fact this JSON.parse produce an error)

How can I access this JSON data?

I'm trying to access some JSON data that I got through an ajax call. I'm not sure how to access this data now though. I want to extract the "test" portion out of the json. Could someone please help me out with this
Image of current output
code sample:
$(".test").on("click", function() {
var dialogID = $(this).attr("id");
console.log(dialogID);
$.ajax({
type: "GET",
url: "test.php?id=" + dialogID,
dataType: "json",
success: function(data) {
console.log(data);
},
error: function() {
console.log("error");
}
});
Assuming the ajax data is stored in a variable called 'data'
data['DATA'][0][0];
If you look at the developer console, you'll notice that 'test' in an item in array at index 0. That array is at index 0 of another array called DATA. DATA is an array in the object returned by the AJAX call.
You can see all the data types next to the variable names in the developer console, i.e 'COLUMNS: Array[1]' on the second line tells you that COLUMNS is an array of length 1.

jQuery AJAX response JSON get child node

i am trying to take the responseJSON from an AJAX call and just extract one element to the variable formDigestValue. I have tried about a dozen ways of trying to return the response, using JSON.parse(), $.parseJSON() and some others, but there are 2 main issues that i cant seem to figure out. I put in a check for if (data.lenght > 0){do something}, response.length, responseJSON, jqXHR, XHR, i cant seem to find the variable that holds the data that would end up sent to success function. I've tried just setting the ajax call to a variable (var y = $.ajax()...) and manipulating it that way.
I just keep reading different articles and trying different ways, but nothing seems to quite get it right and it seems to be fairly simple, but i feel like im just missing something simple on this.
$(document).ready(function () {
var siteURL = "xxx";
var formDigestValue = "";
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(){
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.FormDigestValue;
}
});
...
any advice would be greatly appreciated. For reference, the JSON returned looks like the below. i am trying to figure out if i also need anything extra to get at child nodes, as it looks like it comes back buried a bit (i broke it out with indents just to show the depth):
{
"d":
{
"GetContextWebInformation":
{
"__metadata":
{
"type":"SP.ContextWebInformation"
},
"FormDigestTimeoutSeconds":1800,
"FormDigestValue":"0xADC9732A0652EF933F4dfg1EF9C1B75131456123492CFFB91233261B46F58FD40FF980C475529B663CC654629826ECBACA761558591785D7BA7F3B8C62E2CB72,26 Jun 2015 21:20:10 -0000",
"LibraryVersion":"15.0.4631.1000",
"SiteFullUrl":"http://example.com/",
"SupportedSchemaVersions":
{
"__metadata":
{
"type":"Collection(Edm.String)"
},
"results":["14.0.0.0","15.0.0.0"]
},
"WebFullUrl":"http://www.example.cm"
}
}
}
edit 6/27
Alright, I think between the comment on accessing the child nodes and the rest on passing the argument to success function, ive almost go it. My main thing is, I cannot seem to pass it as an argument. I tried to say it initially, but dont think I write the explanation properly. I tried:
Success: function(responseJSON)...
As well as
Success: function(data)...
But the data never seems to actually enter the function, its null values. I know the json returned, but having issues passing it into success function
Here is a look at firebug when this runs:
Try to add dataType option with json value and don't forget the callback success function take at least one parameter which is the data returned by the server.
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
dataType: 'json',
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(data){
console.log(data);
}
});
Posting from my iPhone, so, it's hard. From the first look, you're not capturing the returned result in success. Try the following.
success: function(responseJSON) {
contextHeaders = $.parseJSON(responseJSON);
if that block of json is what you get returned by $.parseJSON(responseJSON) then you're right, you just need to dig a bit deeper:
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.d.GetContextWebInformation.FormDigestValue;
hope that helps :)

get json data with jquery

Hey guys I would like to know how can I get json data with ajax call.
I tried this but seems won't work :P
First I created a JavaScript file to put inside my json data elements :
var food = [
{'name':'bread', 'price':'7,25'},
{'name':'fish', 'price':'9,00'}
];
I saved it as food.js.
Then I tried to make an ajax call from an another file, this is my code :
$(document).ready(function(){
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food.name;
alert(result);
});
}});
});
Any ideas?
Thanks in advance ;)
Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.
In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:
success: function(data) {
var result = data.food[0].name; // = "bread"
alert(result);
});
try this
$(document).ready(function() {
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food[0].name;
alert(result);
}
});
});
You need to loop through the returned data since it's an array:
$.each(data,function(i,val) {
alert(data[i].name);
});
I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.
Then you can access data.food[0].name;
In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).
Your code is mucth better when you request directly json files.
You probably want to use the getJSON function in jquery : http://api.jquery.com/jquery.getjson/
$.getJSON( "food.json", function( data ) {
//here your callback
}
It will set the datatype to json and the method to GET by default.
You should also use the .json extension and not the js extension for you jsons. And format it like a proper json :
{
"food": [
{
"name": "bread",
"price": 7.25
},
{
"name": "fish",
"price": 9.00
}
],
}
You can use this website to help you format jsons : http://www.jsoneditoronline.org/
The way you are trying to call your element won't work. The data you obtain is an array. In the callback, you can try this :
console.log(data)
console.log(data.food)
console.log(data.food[0])
console.log(data.food[0].name)
console.log(data.food[0].price)
Finally, note that you formatted your numbers with a coma, this is not the way you format numbers in javascript. Use a dot, that way you'll be able to manipulate it as a number.

JQuery getJSON - ajax parseerror

I've tried to parse the following json response with both the JQuery getJSON and ajax:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}]
I've also tried it escaping the "/" characters like this:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview <\/h1><h1>January 29, 2009<\/h1>"}]
When I use the getJSON it dose not execute the callback. So, I tried it with JQuery ajax as follows:
$.ajax({
url: jURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(data){
wId = data.iId;
$("#txtHeading").val(data.heading);
$("#txtBody").val(data.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
},//success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
}
});
The ajax hits the error ans alerts the following:
XMLHttpRequest=[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview </h1><h1>January 29, 2009</h1>"}]
textStatus=parseerror
errorThrown=undefined
Then I tried a simple JQuery get call to return the JSON using the following code:
$.get(jURL,function(data){
var json = eval("("+data+");");
wId = json.iId;
$("#txtHeading").val(json.heading);
$("#txtBody").val(json.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
})
The .get returns the JSON, but the eval comes up with errors no matter how I've modified the JSON (content-type header, other variations of the format, etc.)
What I've come up with is that there seem to be an issue returning the HTML in the JSON and getting it parsed. However, I have hope that I may have missed something that would allow me to get this data via JSON. Does anyone have any ideas?
The JSON string you have is an array with 1 object inside of it, so to access the object you have to access the array first. With a json.php that looks like this:
[
{
"iId": "1",
"heading": "Management Services",
"body": "<h1>Program Overview</h1><h1>January 29, 2009</h1>"
}
]
I just tried this
$.getJSON("json.php", function(json) {
alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
alert(json[0].heading); // "Management Services"
alert(json[0].iId); // "1"
});
I also tried this:
$.get("json.php", function(data){
json = eval(data);
alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
alert(json[0].heading); // "Management Services"
alert(json[0].iId); // "1"
});
And they both worked fine for me.
If anyone is still having problems with this it's because your response needs to be a JSON string and content-type "application/json".
Example for HTTP in asp.net (c#):
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ status: 'success' }");
}
hth,
Matti
Did you try XML-encoding the HTML (i.e. <H1>)?
You could have it return as text and then parse it with the json.org parser
To see if it works any differently
Pleas note that in the question there is a syntax error. The line with
x.overrideMimeType("application/j-son;charset=UTF-8");
should read
x.overrideMimeType("application/json; charset=UTF-8");
This makes a big difference too.
Remove the [], on front and last on JsonData, and it work.
Disabling Firebug Lite fixed this problem for me.
Bug with combination of: jQuery 1.4, ajax/json, Firebug Lite and IE 8
This is a working example and tested!
<script type="text/javascript">
function fetchData() {
var dataurl = "pie.json";
$.ajax({
url: dataurl,
cache: false,
method: 'GET',
dataType: 'json',
success: function(series) {
var data = [];
//alert(series.length);
for (var i=0; i<series.length;i++){
data[i]=series[i];
}
$.plot(
$("#placeholder"),
data,
{
series: {
pie: {
show: true,
label: {
show: true
}
}
},
legend: {
show: true
}
}
);
}
});
//setTimeout(fetchData, 1000);
}
</script>
And the json source is the following (pie.json):
[{ "label": "Series1", "data": 10},
{ "label": "Series2", "data": 30},
{ "label": "Series3", "data": 90},
{ "label": "Series4", "data": 70},
{ "label": "Series5", "data": 80},
{ "label": "Series6", "data": 110}]
First, try to pinpoint if the problem is with general JSON encoding/decoding. try simpler objects, with numbers and plain strings, then with quoted HTML.
After you get JSON working, you really should really consider removing the HTML from there. Much better is to move just data, and leave presentation details to the templates. When using AJAX, that means a hidden template in the HTML, and use jQuery to replicate it and fill with the data. check any of the jQuery template plugins. Of these, jTemplates is a common favorite.
I think you are asking wrong question. Using $.getJSON() is much easier, and if you got problem with it, would be better to ask for $.getJSON() than for $.ajax().
You might also find useful looking at getJSON function source code, because I see, you got a lot of useless stuff there with mimeTypes. That's not the way.
The value you are trying to parse is wrapped in brackets [], which means it is an array. You are trying to eval an array. Try to eval the first element of the array, and it should work...
var json = eval("("+data[0]+");");
Also, I would recommend using the JSON.parse() provided here instead of calling eval() directly.
I received a similar error. Took me a while to find out - little did I know that PHP has not (natively) supported JSON since PHP5.2. Critical reminder...
Yesterday at $. Ajax still no mistakes, today is quoted the mistake, some say parsererror jquery version of the problem, what I use is jquery-1.3.2.min.js, yesterday. This edition also done, today is washed-up. Data sources: no change. Don't know what reason be?
It is maybe because your output buffer is not empty, so AJAX receive bytes which don't belong to the JSON.
Try clean buffer with ob_clean() on server side just before output your json with echo or die(). And you don't need to specify contentType, I think for you default value will work correctly.
I had the same problem and it solve it.
Hope to help you.
in my case, the error was caused by a html tag in the json.
INCORRECT (parsererror)
{"msg": "Gracias,< br >Nos pondremos en contacto."}
CORRECT
{"msg": "Gracias, nos pondremos en contacto."}
BROWSER: IE7/IE8
also try this
$.ajax({
url: url,
data:datas,
success:function(datas, textStatus, jqXHR){
var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));
})};
in my case server responds with unknow character before '{'
Don't use an array box, and make sure you format your data properly:
{"account":{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}}

Categories

Resources