couchDB: download results of list query as attachment - html

I have a list that produces a csv file. Querying that is simple, and if it is queryied from a link, it downloads the response as an attachment (provided the correct headers are sent).
However, I need to POST a potentially large amount of dynamically generated data (an array of keys). It's too large to just append to the url, i need to post the data as, well, data.
My usual ajax query is:
$.ajax({
type: 'POST',
dataType: 'text',
url: '/' + treatmentDatabaseString + '/_design/webview/_list/treatmentTable/treatmentTable?include_docs=true'
data: JSON.stringify({
'keys': keys // DATA THAT NEEDS TO BE POSTED
}),
error: function(status) {
alert('db error (keyed): ' + JSON.stringify(status));
},
success: function(data) {
// ..do stuff
}
});
Is there some way that I can alter the link so that it posts this data? or any other way I can make the result of this query download as an attachment?

If the incoming data is supposed to be JSON, you need to set contentType to application/json in your ajax call.

Related

how to process json post request with nodejs http (no express framework)? [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Raw json is not appearing on the page

I am trying to do a 'get' request through ajax on a url. everything works fine on the console but unable to get the raw json data to display on the page. here data.collections gives me an array of objects. I specifically want raw json data only on the page.
my script is this:
var research;
$.ajax({
url: url,
type: 'GET',
dataType: 'json'})
.done(function(data){
research= JSON.stringfy(data.collections)
});
$('.rsh').html(research);
html is this
<div class = 'rsh'></div>
I want raw json data on page like this but my page is blank.
{
"lab": {
"type": "xy",
"year": "yz",
"team": "yx"
},
"name": "qwerty",
"assistants": 5,
}
edit: this question deals with displaying data in raw json format on the page. Unfortunately the problem in my code was wrong placement of the code. Initial question has nothing to do with asynchronous nature although it is good to know.
var research;
$.ajax({
url: url,
type: 'GET',
dataType: 'json'})
.done(function(data){
research= JSON.stringfy(data.collections)
$('.rsh').html(research);
});
An ajax call is asynchronous so you will need to use the response within the done/success method.

Angular JS POST request not sending data

I am trying to send an JSON object to my webservice which is expecting JSON in the request data.
This my POST call from angularJS
$http({method: 'POST',
url: 'update.htm',
data: $.param($scope.cover),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
// handle
});
Value for cover object
$scope.cover = {id:1, bean:{id:2}}
Iam getting 500 (InvalidPropertyException: Invalid property 'bean[id]' of bean class [BookBean]: Property referenced in indexed property path 'bean[id]' is neither an array nor a List nor a Map;)
In network, it is sending in this way
bean[id]:1
I think it should send like
bean.id:1
How to reslove this issue. Thanks in advance
Looks like the data is getting to the server and is causing an error there. There's a possible duplicate question that's been answered here - Post Nested Object to Spring MVC controller using JSON
Try posting your data like:
$http({method: 'POST',
url: 'update.htm',
data: $scope.cover,
}).success(function (data) {
// handle
});

Why I get null values after a successful upload using JSON?

I need to upload some data on the server using JQuery 1.5.2. These data must be a base64 encoded image, float value and an integer value. Here is my code:
Updated code:
$.ajax({
type: "POST",
datatype: "json",
url: "http://myURL.json",
data: { id: id, image: "jhbjh", lat: 2.6, lng: 3.4},
success: function () {
alert('Successfully uploaded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error on upload: ' + textStatus + " thrown " + errorThrown);
}
});
The only parameter that is successfully uploaded is the integer value id which seems weird to me but the rest of the values are null on the server. I tried to change the values manually for testing reasons (as seen in the code above) but I still get null values. I get null values when my data looks like :
data: { id: id, image: encodedImage, lat: latitude, lng: longitude},
The server's developer insists that the null values are problem of my code and that the server works fine after several testings. Where is my error? Can you please provide your answers with part of code for an example to me?
You have a few errors, first, why are you sending json? That's quite rare to actually send json to a web server. So just remove the line with contentType completely. (Unless you really do send json, in which case you will need some additional code.)
Second you can't send an image via ajax. I assume by image you mean a file uploaded by the user. Unless you only need new browser support, in which case there is a file API you can use via ajax.
If you need to upload a file you have to do it via the hidden iframe method. Use the jQuery Form Plugin to make this easy for you.
If you really are sending json, you will need to encode it yourself into a string and also include processData: false.

Why is my json encoded?

I have the following code which I post a bunch of JSON data to an ASHX file where I will process this data. Somehow the JSON is encoded and I have no clue what encoded it.
$.ajax({
url: '/save_objects_channels.ashx',
data: jsonParams,
contentType: 'application/json',
dataType: 'json',
success: function(data) {
},
error: function (xhr, ajaxOptions, thrownError){
},
complete: function() {
}
});
Here is my sample json that I posted (I generate this as string):
var jsonParams = '[ { objectID: 333, channelID: 3, supplierId: 2, checked: true },{ objectID: 444, channelID: 4, supplierId: 5, checked: true } ]';
jQuery encoded it. You chose to send it as a GET request (which is the default for .ajax()), which transfers all data in the URL as part of the query string. As Clement Herreman also points out, the query string must be encoded.
You might want to switch to type: "POST" in your .ajax() parameters.
GET requests have a length limit that can bite you when the JSON string gets longer. POST requests have virtually no size limit.
Plus, you will cause a data leak: Query strings are written to the web server logs, possibly sensitive data could end up there when you are not careful. POST requests are logged, too. But their payload will not be logged, as it is not part of the URL.
Because URL must be encoded, according the RFC 3986
Hint on how to encode url using Javascript : Encode URL in JavaScript?