Trouble receiving JSON data from nodejs application? - javascript

The below jQuery ajax method makes a call to node.js application that returns a json formatted data. I did check the console and it returns the json in this format
{ "SQLDB_ASSIGNED": 607, "SQLDB_POOLED":285, "SQLDB_RELEVANT":892, "SQLDB_TOTSERVERS":19}
However, when i try to access the element using the key name i get "undefined" on the console ?
Nodejs
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Jquery Ajax
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
for(var i in data)
{
console.log(data[i].SQLDB_ASSIGNED+"---"+data[i].SQLDB_POOLED+"---"+data[i].SQLDB_RELEVANT+"---"+data[i].SQLDB_TOTSERVERS );
}
}
});

Your Node.js part is very weird. You are stringifying a string:
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Why not just this? That's probably what you are looking for:
res.send(JSON.stringify({
SQLDB_ASSIGNED: assigned_tot,
SQLDB_POOLED: pooled_tot,
SQLDB_RELEVANT: relevant_tot,
SQLDB_TOTSERVERS: servertotal
}));
And then in the callback just this:
data.SQLDB_ASSIGNED; // Here you go

I don't know why you are iterating over the keys of the json. You want this:
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
So the code would be:
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
}
});

You seem to be treating the data variable as an array of objects, containing the keys you specify. I guess what you would like to do is this:
for(var key in data) {
console.log(key+": "+data[key]);
}
Or what?

Related

How to call this data piece in Ajax?

I would like to call the meters (732) piece of data from the following json API return:
{"results":1,"data":[{"wind":{"degrees":200,"speed_kts":6,"speed_mph":7,"speed_mps":3,"speed_kph":11},"temperature":{"celsius":16,"fahrenheit":61},"dewpoint":{"celsius":14,"fahrenheit":57},"humidity":{"percent":88},"barometer":{"hg":30.06,"hpa":1018,"kpa":101.79,"mb":1017.92},"visibility":{"miles":"Greater than 6","miles_float":6.21,"meters":"10,000+","meters_float":10000},"ceiling":{"code":"BKN","text":"Broken","feet":2400,"meters":732,"base_feet_agl":2400,"base_meters_agl":732},"elevation":{"feet":256,"meters":78},"location":{"coordinates":[-2.27495,53.353699],"type":"Point"},"icao":"EGCC","station":{"name":"Manchester Airport"},"observed":"2020-07-18T00:50:00.000Z","raw_text":"EGCC 180050Z AUTO 20006KT 9999 BKN024 16/14 Q1018","flight_category":"MVFR","clouds":[{"code":"BKN","text":"Broken","feet":2400,"meters":732,"base_feet_agl":2400,"base_meters_agl":732}],"conditions":[]}]}
This code doesn't seem to call it:
jQuery.ajax({
type: 'GET',
url: 'https://api.checkwx.com/metar/EGCC/decoded',
headers: { 'X-API-Key': 'apikey' },
dataType: 'json',
success: function(data) {
console.log(data)
var ceiling = data.ceiling.feet;
jQuery('#a53feet').html( ceiling );
}
});
Html:
<span id="a53feet"></span>
Is it something in the call pathway (data.ceiling.feet), that isn't right?
The json returned is an array you need to use like below
For accessing feet data
data.data[0].ceiling.feet;
For accessing meters data
data.data[0].ceiling.meters
If you see the console.log, data is an object which has data as an array , so for access the data that you are trying to , you need to do something like below:
data.data[0].ceiling.meters

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

How can I convert a json object to an array in javascript

Here is a snippet of javascript from my C# web MVC application:
$.ajax({
url: 'myurl'
}).done(function(response) {
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The JSON response form this call looks like this
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": {
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}
}
}"
I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": [{
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}]
}
}"
I tried something like this which didn’t work:
$.ajax({
url: 'myurl'
}).done(function(response) {
var tmp;
if (!respose.renditons.rendition.isArray) {
tmp = respose.renditions.renditon;
respose.renditon = [];
respose.renditon.push(tmp);
}
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.
Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code
Try this:
$.ajax({
url: 'myurl'
}).done(function(response) {
var json = JSON.parse(response);
if(!Array.isArray(json.renditions.rendition)) {
json.renditions.rendition = [json.renditions.rendition];
}
return json;
});
Fiddle demo (kind of...)
You can check if the object is an array using this:
Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'
And you can simplify the conversion to an array -- just wrap it as an array using x = [x]:
if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
response.renditions.rendition = [response.renditions.rendition];
}
Fiddle demo.
add data type JSON to your ajax post. example
$.ajax({type: "POST",
url: URL,
data: PARAMS,
success: function(data){
//json is changed to array because of datatype JSON
alert(data.renditions);
},
beforeSend: function (XMLHttpRequest) {
/* do something or leave empty */
},
complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },
dataType: "json"}
);

ember.js and mongoDB find object by id

Cheers!
I get Foo (for example) object from remote server with an ID, which looks like this:
id: "5110e8b5a8fefe71e0000197"
But when I do:
App.Foo.find("5110e8b5a8fefe71e0000197")
it returns array of objects, which is wrong, 'cause all ID's are uniq in mongo.
> Array[112]
So, how to make it work?
UPDATE:
My find function:
App.Foo.reopenClass({
allFoos: [],
find: function(){
$.ajax({
url: 'http://address/foos.json',
dataType: 'jsonp',
context: this,
success: function(data){
data.forEach(function(foo){
this.allFoos.addObject(App.Foo.create(foo))
}, this)
}
})
return this.allFoos;
}
});
Try using this:
App.Foo.findOne({_id: "5110e8b5a8fefe71e0000197"})

Send array with $.post

I'm trying to execute a $.post() function with an array variable that contains the data, but it seams that I'm doing something wrong because it won't go or it's not possible
var parameters = [menu_name, file_name, status, access, parent, classes];
console.log(parameters);
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json'); //Doesn't work
Firebug debug: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
So, which would be the propper way of doing it (if possible)?
i am using for such kind of issues always the $.ajax form like this:
$.ajax({
url: 'do.php',
data: {
myarray: yourarray
},
dataType: 'json',
traditional: true,
success: function(data) {
alert('Load was performed.');
}
});
the traditional is very important by transfering arrays as data.
Could be the variables in the parameters array
Having ran your code and supplemented the parameters for something like:
var parameters = ['foo','bar'];
It seems to work fine. I think the problem must be in the variables that you are passing as part of the array. i.e. are menu_name, file_name, status, access, parent and classes variables all as you expect them to be? e.g. console log them and see what they are coming out as. One might be an object which doesn't convert to json.
Use JSON.stringify()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
$.post('do.php', {
OP: 'new_menu',
data: JSON.stringify(parameters)
},
function(result) {
console.log(result);
},
'json'
);
And then, in the server-side use json_decode() to convert to a php array.
http://php.net/manual/es/function.json-decode.php
Ok, so with the help of these StackOverflow fellows I managed to make it work just the way I wanted:
var parameters = {
'name': menu_name.val(),
'file': file_name.val(),
'status': status.val(),
'group': group.val(),
'parent': parent.val(),
'classes': classes.val()
};
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json');

Categories

Resources