Why is my json encoded? - json

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?

Related

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.

Extjs is passing my cfc a json string that I can not read

I am playing with the ExtJs4 cartracker application written by existdisolve. I was able to change his queries from rest requests to ajax requests. I also modified the api calls to use ajax to make ajax requests for updates.
I am not getting form or url data passed to my cfc. Instead, in firebug I see JSON passed. I am confused if it is not passed in the form or the url, how is this passed and how do I get to the data? I have tried deserialized the form and url and dumping these after the deserialize and I am told that it is not json.
Where would I find the json?
I am not allowed to post a picture. But it looks like this in the xhr window:
JSON
Active true
ColorID null
Shortname red
Longname Blood Red
So if it is being passed why can I not get to it?
Edit:
#existdissolve - I replaced the rest.js with ajax.js which looks like this:
/**
* Abstract REST proxy
*/
Ext.define('CarTracker6.proxy.Ajax', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.baseajax',
/*format: 'json',*/
limitParam: 'max',
startParam: 'offset',
sortParam: 'sortorder',
writer : {
type : 'ajax',
encode : false,
writeAllFields : true,
root : 'data',
allowSingle : true,
batch : false,
method: 'post',
params: { record: 'record' },
writeRecords : function(request, data) {
request.jsonData = data;
return request;
}
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'count'
},
api: {
read: 'api/option/colors.cfc?method=getcolors',
create: 'api/option/colors.cfc?method=addcolors',
update: 'api/option/colors.cfc?method=updatecolors',
destroy: 'api/option/colors.cfc?method=deletecolors'
}
});
My read works perfectly and I can call the correct cfcs for colors, statuses, etc. and retrieve the requisite data. I am looking to pass parameters to the CFCs and that is not working.
see http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.writer.Json-cfg-encode:
if the encode property of your writer is set to false, all data is sent as raw post body. Instead, you can use
encode: true,
root: 'data', // must be set if encode is true

couchDB: download results of list query as attachment

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.

Posting JSON with JQuery

Trying to get JQuery to post JSON to a server:
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "json",
data: {"foo": "bar"},
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});
Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.
I thought specifying either the dataType or contentType params would do the trick, but no.
Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]
Thanks!
You could use json2.js:
data: JSON.stringify({"foo": "bar"})
Datatype is for returned data. Contenttype is not applicable, see here
It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.
You will also need to access the string on server side, for that if you are using java I can recommened google's gson

Using jQuery and JSON with AJAX responseText?

Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?
here's the code that i'm using:
json response: {"clients": []}
$.ajax({
type: "POST",
url: "/myurl/whatever.php",
data: myData,
dataType: "json",
success: function(msg){
status.html(msg[0]);
},
error: function(msg) {
status.html("Error: " + msg[0]);
}
});
is the use of msg[0] correct if i want to output the json response or am i missing something?
how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.
thanks, all!
As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:
var xhr = $.ajax( {
url:' someInfo.php',
data: 'which=squirrels',
asynch: true
} );
var resp = xhr.responseText;
The response text will contain a json string, which would need to be converted to an object to be of any use.
If you want to use the response as a json object directly within your success: function, do as #cloudhead suggested, and use msg. The dataType : "json" in your options takes care of the conversion for you.
If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].