I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)
Related
I have a JSON local file that looks like:
{
"sites" : [
{
"name" : "Somename",
"url" : "https://url.com",
"api" : "http://url.com/api",
},
{
"name" : "Somename2",
"url" : "https://url2.com",
"api" : "http://url2.com/api",
}
}
Each api has a single integer data that I need to store in the database. How do I iterate such JSON in Javascript? As soon, as I'm able to retrieve that api url I will be able to write another function and get the integer i want. What I've tried was:
function getNetworkData(){
$.getJSON('../json/sites/site-list.json', function(data) {
var sites = JSON.parse(data);
sites.forEach(function(data){
console.log(data.sites[0].name)
});
});
}
...but that just doesn't work. I keep getting an error:
Unexpected token o in JSON at position 1
The function $.getJSON already parses the response from the server/source.
So, you don't need to parse it using JSON.parse, further, you're trying to loop using the array as follow:
sites.forEach
What you really want is loop the attribute sites:
data.sites.forEach(function(s){
console.log(s.name);
});
You already got JSON, there is no need to parse. Refer jQuery.getJSON
Update from
var sites = JSON.parse(data);
sites.forEach(function(data){
console.log(data.sites[0].name)
});
to
data.sites.forEach(function(site){
console.log(site.name); // prints name
console.log(site.api); // prints api
});
Like this:
function getNetworkData(){
$.getJSON('../json/sites/site-list.json', function(data) {
data.sites.forEach(function(site){
console.log(site.name)
});
});
}
The object you are looping through doesn't need the index.
site is already equal to sites[0] on the first loop, sites[1] on the second loop etc, so you just need site.name
Skip JSON.parse(data); You will get an object with $.getJSON() that you can manipulate. See getJson
I have the following json data that looks like this...
What I am trying to do is store the temp numbers into a javascript array to display on a graph. This is my code that I was working on...
$.ajax({
type: 'GET',
url: "http://api.openweathermap.org/data/2.5/forecast?q=Redlands,us&mode=json&units=imperial&cnt=20&APPID=5eea63b2ee3505c58713d9149832d4c5",
dataType: 'json',
success: function(data){
//console.log(data.list[0].main.temp);
//trying to parse through data for graph
var date = [];
$.each(data,function(index, data){
date.append(data.list[index].main.temp);
});
}
});
But it is not working I get the following error...
Uncaught TypeError: Cannot read property 'city' of undefined
Anyone know how I can fix this?
i see working , same from Erik Engervall, i change var data for current
$.each(data.list,function(index, current){
date.push(current.main.temp);
});
It seems you're iterating over the entire data object, whereas I believe you only wish to iterate over the data.list:
$.each(data.list, function(index, val) {
date.push(val.main.temp);
});
Also, JavaScript arrays uses push.
Updated answer after Mikel.
You need to use JSON.parse().
var dataList = JSON.parse(data).list;
I have a front-page.php template which lists the 5 latest posts along with some custom post types in between. When one clicks on the more button at the bottom it needs to ajax load more posts.
So I created a loop-home.php file according to this tutorial
I couldn't use this code by default because I have a nested loop on the first load of homepage and this script messes it up.
So I wrote a new query to ajax OLDER posts only. I collected the post ids of the posts already present when the page loads and stored it in an array.
I now need to use this array in the query of loop-home.php
I am using this method because offset does not work with pagination and I need to pass these IDs to post__not_in parameter in the query.
Method 1:
I tried (in loop-home.php)
$exempt = $_REQUEST['exemptArray'];
But it returns NULL.
Method 2:(Using Ajax)
I tried (in front-page.php)-
<script>
var exemptArray = '<?php echo json_encode($exemptions); ?>';
</script>
Then I went to script.js and added-
//create json object from the var array
var jsonArray = JSON.stringify(exemptArray);
var dataToPost = { 'jsonArray':jsonArray };
//send POST data to PHP and handle response
$.ajax({
type: 'POST',
url: loopHome, //stored path in variable. working.
data: dataToPost,
success: function (data) {
console.log('I have already sent it.'); //I am getting this log. Working.
}
});
Then in loop-home.php-
$exempt = json_decode($_POST['jsonArray']);
Still getting NULL on var_dump($exempt)
What am I doing wrong?
Try this
You JS:
$.ajax({
type:'POST',
url:'foo.php',
data:{myArr:exemptArray},
dataType:'JSON',
success:function(result){
console.log(result);
},
error:function(data){
console.log(JSON.stringify(result));
}
});
Your php page:
$input=$_POST['myArr'];
$exempt=json_encode($input);
In your console you will get an array. [object object] is a reference to an associative array.So in the above code result is same as exemptArray.Try something like this you will be able to.I could not find your array composition anywhere so i used exemtarray itself.
I am using the Django framework to build a website.
In the Python file (views.py) I send to the Javascript function an array that has been transformed to json data
Python:
json_data=[1,2,3]
return HttpResponse(json.dumps(json_data), mimetype='application/json')
Then, in Javascript I display the json data in the html.
JavaScript:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
$('.square').append('<p> ' + json_data + ' </p>');});
};
So far everything works. However, I would like to convert the "json_data", which I believe is a string, into an array.
I tried doing this:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var array = json_data.split(',');
$('.square').append('<p> ' + array[0]+ ' </p>');});
};
Unfortunately, this doesn't work.
Can someone please explain to me what could I do to convert the "json_data" variable into an array in JavaScript?
Thanks a lot.
When you send around data in JSON format it is a string (the main data), but a string formated in such a way that it's easy to recover the data with the original types (ie, your array). Javascript and jquery have different ways to do that. Using jQuery,getJSON is probably the most direct:
http://api.jquery.com/jQuery.getJSON/
You can use your browsers javascript console to see what exactly do your JS variables look like.
"this doesn't work" it's too vague...
Anyway, if I understood your problem, you are dealing with a string, not a JavaScript array... you have to evaluate the data returned from the ajax call:
var theJavaScriptArray = eval('(' + json_data + ')');
or better... use jQuery.ajax and specify json as dataType: jquery doc
In the end, thanks to Zah I discovered the "javascript console", which I didn't know it existed.
I could see that the error was that the "json_data" variable was not a string.
So this is the solution that worked for me:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var b=json_data.toString().split(',');
$('.square').append('<p> ' + b[0] + ' </p>');
});
};
There is a shorthand in jQuery to parse the json string automatically: jQuery.getJSON()
$.getJSON('/xhr_test/json/', function(data) {
console.log(data); // Here data is already a JavaScript object
});
This is basically the same as:
$.ajax({
url: "/xhr_test/json/",
dataType: "json",
success: function(data) {
console.log(data); // Here data is already a JavaScript object
}
});
Which again is about the same as:
$.ajax({
url: "/xhr_test/json/",
success: function(data) {
var json = $.parseJSON(data); // Here data is a string
console.log(data); // And json is JavaScript object
}
});
Trying to pull data from parse.com and use underscore.js I tried using this to build a table of the data. When I run it with hard coded json it works but when I try running it with pulled data returns an empty table.
Parse.initialize("", "");
var allDeals = Parse.Object.extend("Deal");
var query = new Parse.Query(allDeals);
query.find({
success: function(results){
var deals = JSON.stringify(results);
var template = $("#usageList").html();
$("#target").html(_.template(template,{deals:deals}));
},
error: function(error) {
alert('something was wrong');
}
});
Thanks in advance!
Like #mu said it would be easier to see whats in results..
But I have run into this with Parse before. Taking a guess.. You can try this
$('#target').html(_.template(template, { deals: results.models }));
"results" is a backbone collection and "models" holds the array of objects you are after.
Presumably you're getting a JavaScript object of some sort in results in your success callback. Then you serialize that to a JSON string with:
var deals = JSON.stringify(results);
That leaves you with a string in deals and your template probably doesn't know what to do with a string, it probably wants an object or whatever was in results in the first place. Try skipping the stringification and just feed results straight into the template:
$('#target').html(_.template(template, { deals: results }));