JSON data logging to buffer and PUT to server - javascript

I have a javascript function which generates JSON data at every certain second and then PUT it to a cloud server. Now I don't want to POST in realtime, rather I want to log this data in a buffer and say after n number of data log I will PUT to cloud. For example I want to log 50 data point in 10 second and then with timestamp I will PUT to a server
Now JSON data is passed through var fromDatan. JSON data format is
{"values": [ { "at": "2014-08-17T12:00:00Z", "value": "15" }]}
This is a single instance which is passing through say var fromDatan and being PUT in cloud.
Now I want to log say n number of JSON data. ie.
{ "values": [ { "at": "2014-08-17T12:00:00Z", "value": "15" }, { "at": "2014-08-18T12:00:00Z", "value": "20" }, { "at": "2014-08-19T12:00:00Z", "value": "25" } ] }
And then I will PUT to cloud. This is my PUT code for real time which is working:
$.ajax({
url: "https://abcd.com",
headers: {
"X-API-KEY": "23dq3dq3ddbb16a7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
So please let me know how to do this. Help me out

the code that runs every second should do:
fromDatan.values.push({
at: timestamp,
value: value
});
if (fromDatan.values.length >= 50) {
$.ajax( {
...
});
fromDatan.values = [];
};

Related

my JSON is not practical and I want to change it, how can I do so?

Problem: my JSON isn't practical and I want to change it. As you can see my JSON looks strange, but somehow it's valid JSON (checked with JSONLint). I have input fields which are in containers with their own unique id (they increment). I was wondering if it's possible to send the data inserted into the input fields together so when I fetch it, it will stay together.
how my JSON looks like right now:
{
"main_object": {
"id": "new",
"formData": {
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"question_takeAudio_exerciseWord[0": "ExampleForStackOverflow",
"Syllablescounter[0": "Example",
"Syllablescounter[1": "Example1",
"question_takeAudio_exerciseWord[1": "SecondExampleForStackOverflow",
"Syllablescounter[2": "Second",
"Syllablescounter[3": "Example"
}
}
}
what I am looking and hoping to achieve:
{ "main_object":
{
"id": "new",
"formData": [
{
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"Word": "ExampleForStackOverflow",
"Syllables":["Example", "Example1"]
},
{
"Word": "SecondExampleForStackOverflow",
"Syllables": ["Second", "Example"]
}
]
}
};
https://jsfiddle.net/StackOverflowAccount/sa2eowhh/ I have a fiddle so you can see what I mean. When you click on the green + button it adds a whole field. This is a container that has an ID, I am trying to keep everything with the same ID with each other in the JSON file, so when I fetch it to my front-end it "knows" which syllables are part of the exercise word.
I have an ajax call which I think causes my JSON file to look like what I have right now.
my ajax call:
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: JSON.parse('{"' + decodeURI($('#my_form').serialize()).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
},
dataType: 'json',
}).done(function(response) {
});
});
}
Thanks!

Arrays in AJAX request JSON object data

I am sending a request to a Node/Express server using jQuery thats data is a JSON object containing an array:
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: data,
dataType: 'json'
});
The request itself is working fine, however the server is reporting the data as:
{
name: 'James Jamesy',
'children[0][name]': 'Little James',
'children[0][age]': '4',
'children[1][name]': 'Medium James',
'children[1][age]': '6',
'children[2][name]': 'Graham',
'children[2][age]': '8'
}
Now I've figured out that I can get my desired result by instead stringifying the children array:
var data = {
"name": "James Jamesy",
"children": JSON.stringify([ ... ])
}
And then JSON.parse()ing it on the server.
However I am hoping someone can explain why the array is converted as it is in the request, and whether I should be handling this a different way? As in this instance converting the single array is fine, but going forward I might have semi-complex objects I'm looking to send to the server.
Thanks in advance!
EDIT: Additionally and strangely(?), if I send the JSON result back as the passed JSON, it works perfectly:
res.json(JSON.parse(req.body.categories));
The browser logs out the object and I can manipulate it perfectly fine.
You weren't passing a JSON string through ajax which is why you couldn't handle the data on the back end.
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: JSON.stringify(data),
contentType: 'application/json', // for request
dataType: 'json' // for response
});

Construct new array based on lastChangedDate

I have a refreshdata() function which executes a call to get IDs of certain events:
function refreshdata()
{
$http({
url: “…/GetIDs”,
method: "POST",
data: jsonData,
dataType: "json",
timeout: 7000,
contentType: 'application/json; charset=utf-8'
}).success(function(data, status, headers, config) {
responseNew=data.d;
meetings = JSON.parse(responseNew);
console.log("Got meetings");
meetingsanddetails(meetings);
}).error(function(data, status, headers, config) {
alert("Unable to refresh data.”);
});
}
meetings is something like:
{
"Result":"success",
"Key":"12345",
"Data":[
{"ID":"GFDCV34","lastChangedDate":"2015-12-03 11:14:27"},
{"ID":"IDJHE23","lastChangedDate":"2015-12-03 15:17:47"},
{"ID":"KDJBD34","lastChangedDate":"2015-12-03 05:25:11"}
]
}
Next, I do meetingsanddetails(meetings):
res = meetings;
var i = 0;
var tmp = [];
promises = [];
res.Data.map(function (val) {
promises.push(getdetails2(val.ID).then(function (data) {
tmp = JSON.parse(data);
Object.keys(tmp.Data[0]).map(function (v, j) {
val[v] = tmp.Data[0][v];
});
}, function (error) {
console.log(error)
}));
});
$q.all(promises).then(function () {
$timeout(function () {$ionicLoading.hide()}, 500);
$window.localStorage['data'] = JSON.stringify(res);
});
res is now something like:
{
"Result": "success",
"Key": "12345",
"Data":[
{
"ID": "GFDCV34",
"name": "Name of event 1",
"date": "date of event 1",
"location": "location of event 1",
"lastChangedDate": "2015-12-03 11:14:27"
},
{
"ID": "IDJHE23",
"name": "Name of event 2",
"date": "date of event 2",
"location": "location of event 2",
"lastChangedDate": "2015-12-03 15:17:47"
},
{
"ID": "KDJBD34",
"name": "Name of event 3",
"date": "date of event 3",
"location": "location of event 3",
"lastChangedDate":"2015-12-03 05:25:11"
}
]
}
(credit to maurycy)
(Info: getdetails2(id) returns the details of an event with a given ID).
This works fine, but the getdetails2 calls take a long time to load. That is way I would like to make it work like this:
If …/GetIDs returns IDs that weren’t already in $window.localStorage['data'], they should be added with their details.
The IDs that …/GetIDs returns that were already in $window.localStorage['data’], should only be updated if the lastChangedDate of the new call is more recent.
IDs that are present in $window.localStorage['data’], but not in the new call, should be deleted.
Anyone who can point me in the right direction? I keep messing up this array hocus pocus.
First of all, don't rely on localStorage: in private mode in Safari it does not work, so you need to have some fallback to prevent errors.
What you want to achieve is a caching thing. You have two possibilities: do it on your own which would take some time and probably will have some bugs (I did it couple of times and it was not fun at all) or use ready solutions, e.g. this advanced angular-cache. It allows to choose the storage type, can be natively used with $http / $resource and allows operations with the cache such as deleting cached responses (that's what you would need to do when you get a newer timestamp). It is quite easy to use, just check the docs and examples.

How get first image from all posts with ajax

I have this code which spits out all the content for the first post only. I would like it to spit out the first image from all posts.
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
$(".x").html(postBody);
}});
And this is a ajax response:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": { ... },
"posts": [
{
"blog_name": "citriccomics",
"id": 3507845453,
"post_url": "http:\/\/citriccomics.tumblr.com\/post\/3507845453",
"type": "text",
"date": "2011-02-25 20:27:00 GMT",
"timestamp": 1298665620,
"state": "published",
"format": "html",
"reblog_key": "b0baQtsl",
"tags": [
"tumblrize",
"milky dog",
"mini comic"
],
"note_count": 14,
"title": "Milky Dog",
"body": "<p><img src=\"http:\/\/media.tumblr.com\
/tumblr_lh6x8d7LBB1qa6gy3.jpg\"\/><a href=\"http:\/\
/citriccomics.com\/blog\/?p=487\" target=\"_blank\">TO READ
THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired by
something <a href=\"http:\/\/gunadie.com\/naomi\"
target=\"_blank\">Naomi Gee<\/a> wrote on twitter, I really
liked the hash tag <a href=\"http:\/\/twitter.com\/
search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
and quickly came up with a little comic about it. You can
(and should) follow Naomi on twitter <a href=\"http:\/\
/twitter.com\/ngun\" target=\"_blank\">#ngun<\/a> I'm on
twitter as well <a href=\"http:\/\/twitter.com\
/weflewairplanes\"target=\"_blank\">#weflewairplanes<\/a>
<\/p>\n\nAlso, if you’re a Reddit user (or even if
you're not) I submitted this there, if you could up vote
it I'd be super grateful just <a href=\"http:\/\
/tinyurl.com\/5wj3tqz\" target=\"_blank\">CLICK HERE<\/a>"
},
...
],
"total_posts": 3
}
}
As you can see, images in the body are wrapped with tags.
How i get the images?
Using jQuery, see the sample code:
$(results.response.posts[0].body).find('img').first();
It is probably not the best alternative, but it should do.
If you wanna do it for multiple posts use array of images:
var img = new Array();
$.each(results.response.posts, function (ix,el){
img.push($(el.body).find('img').first());
})
try this:
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
var html = $(postBody);
var firstImage = $(postBody).find("img:first");
}});
var $ct = $('.x');
$.ajax({
url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function (results) {
console.log(results);
$.each(results.response.posts, function (_, post) {
$(post.body).find('img:first').appendTo($ct)
})
}
});

JSONP Object Error

I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?
This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.

Categories

Resources