How send JSON data on $.post() | jQuery [duplicate] - javascript

This question already has answers here:
Jquery - How to make $.post() use contentType=application/json?
(17 answers)
Closed 6 years ago.
I tried in 2 ways:
saving the json on a var
var dataLog = JSON.stringify( {
"clientId": "1",
"sensor": "Temp",
"dateStart": "2016-09-03 00:00:00",
"dateEnd": "2016-09-03 00:59:59"
} );
$.post(data , {dataLog})
.done(function( data ) {
console.table(data);
});
and adding the same json directly into the data parameter
$.post( url, {
"clientId": "1",
"sensor": "Temp",
"dateStart": "2016-09-03 00:00:00",
"dateEnd": "2016-09-03 00:59:59"
})
.done(function( data ) {
console.log(data);
});
but none of the 2 options works, it is possible or im doing something wrong?

here one example
var promise = $.ajax({
url: url,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: dataLog
});

Related

Cant retrieve the JSON using Ajax

My JSON:
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
Ajax call:
$.ajax({
type: "POST",
url: my_url,
async: false,
success: function(result){
alert(JSON.stringify(result));
message= JSON.parse(result);
alert(message.Schedule.channel.length);
}
});
My json is coming. First alert message is giving my JSON. When i parse that json, error is coming like
Uncaught SyntaxError: Unexpected token o
Location: jquery.min.js.2
I tried solving this issue. Couldnt able to figure out where it is going wrong.
Can anyone help me
Remove the comas after "prepaid_price": 15 and "prepaid_price": 7. You are also missing a closing } at the end of your JSON.
You can validate your JSON here: http://www.jsoneditoronline.org/
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
You can use dataType: 'json', in your AJAX-call, then your JSON will be parsed automatically and you don't need to call message = JSON.parse(result); because your result will be already an Object.
Then you can call alert(result.Schedule.channel.length); direct.
Your code would look like:
$.ajax({
type: "POST",
url: my_url,
async: false,
dataType: 'json',
success: function(result){
alert(result.Schedule.channel.length);
}
});

How to extract a JSON object from the resulting JSON array? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
I have the following code to get the results of a query. The query results are in the form of JSON.
$.ajax({
url: ..... //url//...,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
"type": "daysofyear",
"entity": {
"year": "2015"
}
}),
type: "POST",
dataType: "json",
success: function(result) {
if ((result) && (result.isSuccess == true)) {
alert("SUCCESS");
alert(json.entity.day);
}
},
});
The returned JSON is:
{
"isSuccess": true,
"results": [{
"jsonClass": "RuleSuccess",
"message": "Found mapping for year: 2015",
"rule": {
"name": "Year rule",
"metadata": {}
},
"entity": {
"year": "2015",
"month": "December",
"day": "Saturday"
}
}]
}
Im basically trying to extract the value of month, year, day separately and display them alone using
alert(json.entity.day);
Please advice.
Update
var a =JSON.parse('{"isSuccess":true,"results":[{"jsonClass":"RuleSuccess","message":"Found mapping for year: 2015","rule": {"name":"Year rule","metadata":{}}, "entity":{"year":"2015", "month":"December", "day":"Saturday"}}]}') ;
alert(a.results[0].entity.day);
Original
Use
alert(result[0].rule.entity.day);
try this:
obj = JSON.parse(json);
console.log(obj[0].rule.entity.day);

JSON data logging to buffer and PUT to server

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 = [];
};

Attempting to parse or assign JSON response: Response is read as [object Object] [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Using Flickr API, Javascript/JQuery, and AJAX, I have the follow code:
function getRequest(arguments)
{
var requestinfo;
$.ajax({
type: 'GET',
url: flickrurl + '&'+ arguments + '&jsoncallback=jsonCallback',
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (json)
{
requestinfo = json;
//Parse attempt requestinfo = $.parseJSON(json);
//Old method return json;
}
});
return requestinfo;
}
When the response is received and I attempt to assign the json (the response) data to the variable, requestinfo, (or even if I do a straight 'return json' line) I get an error indicating the returned value is undefined. Upon fooling with the success function, I notice that any attempts to parse the response fails due to 'json' being read as [object Object] instead of the JSON response.
Is the response already in array format? If not, how can I get it to that point?
Here is an example JSON response (there are multiple types as different requests are needed to receive all needed information (Flickr API):
{
"collections": {
"collection": [
{
"id": "122388635-72157643471284884",
"title": "Test Gallery 2",
"description": "Test 2",
"iconlarge": "/images/collection_default_l.gif",
"iconsmall": "/images/collection_default_s.gif",
"set": [
{
"id": "72157643471292484",
"title": "Set 1",
"description": ""
}
]
},
{
"id": "122388635-72157643469075734",
"title": "Test Gallery 1",
"description": "Bing Photos",
"iconlarge": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_l.jpg",
"iconsmall": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_s.jpg",
"set": [
{
"id": "72157643469056814",
"title": "Test Gallery 1",
"description": "Bing Backgrounds"
}
]
}
]
},
"stat": "ok"
}
So how do I pass the received data to other functions without a disruption in the data?
Code should be much like below
success: function (collections)
{
$.each(collections,function(index,item){
var i=0;
$.each(item.conllection[i],function(index,item){
alert(item.id);
i++;
});
});

Disjunction of filters in ajax, request to flask-restless

I have a backend application with flask-restless which replies some json data. It is properly set.
I request these data from javascript by $.ajax function. It works perfect with one filter, I need more filters, but I don't know how them set.
Example with one filter (it works):
var page = 1;
var filters = [{"name": "device", "op": "eq", "val": 1}];
var url = 'http://..../results?page=' + page;
$.ajax({
url: url,
data: {"q": JSON.stringify({"filters": filters})},
dataType: "jsonp",
type: "GET",
contentType: "application/jsonp",
success: function(responseData, textStatus, XMLHttpRequest) {...}
});
For 2 filters I tried (it doesn't work):
var page = 1;
var filters = [{"name": "device", "op": "eq", "val": 1},{"name": "device", "op": "eq", "val": 2}];
var url = 'http://..../results?page=' + page;
$.ajax({
url: url,
data: {"q": JSON.stringify({"filters": filters},{"disjunction":true})},
dataType: "jsonp",
type: "GET",
contentType: "application/jsonp",
success: function(responseData, textStatus, XMLHttpRequest) {...}
});
Has anyone of you ever had similar problem?
You need to give JSON.stringify an array to convert to string.
data: {"q": JSON.stringify([{"filters": filters},{"disjunction":true}])},

Categories

Resources