data.forEach is not a function - javascript

This is my json
[
"59191", "TypeAV - Canada", "Available",
"422129", "TypeAA - Italy", "Available",
"959191", "TypeBB - USA", "N/A",
"6D968C", "TypeAV - Canada", "Available"
]
and js
$.ajax({url: 'test.json'}).done(function(data) {
$.each(myArr, function () {
data.forEach(function (line) {
//do something
});
})
})
I get a Uncaught TypeError: data.forEach is not a function. How to fix this?

data is apparently not an array. $.ajax will automatically parse the response as JSON if the server sends the Content-type: application/json, but it must not be doing this. Since jQuery doesn't know that the response should be parsed as JSON, it simply passes the string response to the callback function.
So you need to tell JQuery that it's JSON and needs to be parsed. The easiest way is to use $.getJSON instead of $.ajax, since you're not passing any of the complex options to $.ajax.
$.getJSON('test.json', function(data) {
...
});
You can also use the dataType: option to `$.ajax.
$.ajax({
url: "test.json",
dataType: "json"
}, function(data) {
...
});

Related

JSON Data cannot be stored in variable

Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error

Results From A JSON Call to Variable

I am trying to get a ID from a JSON call, and not sure what the issue is. I have a Callback function set up to set a global variable as such.
GOAL: Make a call to a DB, get the ID from the results returning.
STEP 1 - Make call to JSON and Parse Results
callAjaxGet(<set url>,function(myReturn){
var noteID = ''
$.each(myReturn.results, function(i, note){
noteID = JSON.parse(note.id);
});
})
STEP 2 - JSON/Callback Function
function callAjaxGet(url, callBack){
$.ajax({
url: url,
type: 'GET',
timeout: 10000,
success: function(data,textStatus,xhr){
return callBack(xhr);
},
error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
STEP 3 - The Returning JSON
{
"next": "http://selleck.beta.org/playlist/notes/?limit=20&offset=20&play=437",
"previous": null,
"results": [
{
"id": 258,
"url": "/playlist/notes/258/",
"content": "testing",
"play": 437
}
]
}
No matter what I'm doing, the noteID comes back without value. I've looked in Google Development Tools, XHR, and can see the JSON coming back, so thinking I've misunderstood something.
Thank you for any thoughts and suggestions
Steve
Figured it out. Two things were wrong.
Was using XHR instead of Data
Wasn't parsing the JSON properly, the ID is in an array, so had to set the first entry, so
noteID = myReturn.results[0].id;
Thanks A.Sharma and ron tornambe for the pointer on the XHR error
Steve

jQuery json ajax function

I am having a kind of a weird problem, or maybe I do not understand how js and jQuery is working.
I have a small js that is sending an id and a value using AJAX. After a lot of experimentation I finally found a working solution which is:
$.post('dashboard/xhrDeleteListing', "id=" + id, function() {
alert(1);
});
However, I would like to use json format for the data part of the call. So what I did (to make sure that my JSON is correct) was the following:
var myJSON = {
id: id
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
But this didn't work. First, php server didn't get anything (nothing in $_POST), second, the callback function didn't run (alert(1) was never executed). To my surprise, the following call did create a $_POST['id'] value:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
but again the callback function didn't run. It only run after removal of 'json' datatype argument).
The version of jQuery is v1.11.0.
Can anyone help me to figure out what am I doing wrong?
Regards,
The important point here is when you do this like:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
the 'json' paramter is the dataType of data expected from the server, not from you to send.
It means in your backend after doing your server side task you have to return a valid json string but it seems you want to do a server action without any return value, that's why you have to remove 'json' from your arguments.
var myJSON = {
"id": "id"
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
Try this :
$.ajax({
url: 'dashboard/xhrDeleteListing',
type : 'POST',
dataType : 'json',
data: {
'id':id,
},
success : function(callback_record) {
alert(callback_record);
}
});

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Categories