I'm trying to send json string in the get request to the server, here is how it looks before encoding :
filters={"groupOp":"AND","rules":[{"field":"countrycode","op":"eq","data":"ARG"}]}
Naturally I end up with null pointer when trying to get this json string, then I googled this encodeURIComponent and it partially encodes this string like this :
filters={"groupOp"%3A"AND"%2C"rules"%3A[{"field"%3A"countrycode"%2C"op"%3A"eq"%2C"data"%3A"ARG"}]}
But this is how it supposed to be in order to work :
filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22countrycode%22%2C%22op%22%3A%22eq%22%2C%22data%22%3A%22ARG%22%7D%5D%7D
How do I get this, entirely encoded string so I can read it at server side properly ?
Reason why I used get instead of post
I'm sending this filter(json) content to the server side, web service gets data from the database and returns pdf document.
Using post, I'm able to send correct data and the response is successfully displayed in my firebug console. But I need to return pdf doc to override the current page or open new window/tab and return in that one.
I think you're overworking this problem. Or encoding too many times. Or something.
You've got a JSON string, and you are trying to JSON encode it. That seems...unhelpful.
A better approach might be to produce a Javascript object, then JSON.Stringify that, and then transmit it as a parameter.
var thing = {
groupOp : "AND",
rules : [
{ field : "countrycode", op : "eq", data : "ARG" },
...
],
...
};
var stringrep = JSON.stringify(thing);
// post via jQuery
$.ajax({
type: 'POST',
url: url,
data: stringrep,
dataType: 'json'
success: function() { ... },
});
Normally for a JSON stringified message to or from the server, you'd want to use HTTP POST. HTTP GET puts all "parameters" in the URL; there is no message body. In contrast, HTTP POST allows you to attach a message body to the HTTP message, which can be "anything". With that approach, you don't need to url-encode the quotes and spaces; the JSON message just gets transmitted as the message body of the HTTP message.
HTTP POST is the way applications upload images, or transmit XML documents, and so on. Anything complex gets transmitted via POST.
var filtersParameter = 'filters=' + encodeURI(JSON.stringify(filters));
var filtersParameter = 'filters=' + atob(JSON.stringify(filters));
Note: atob() method uses base64 algorithm to encode the data. This encoded data can be easily passed to a server where it can be decoded using corresponding decoding methods (in python base64.b64decode(encoded_string) is used).
Related
I am having problem extracting data sent from the Ajax call to the python flask backend.
I am able to extract the key:value string pair only from the request.args object. But the problem is the data I am sending is of mixed type :
e.g. data:{'data':'stringdata','Email':['abc#example.com','def#example.com'],'checkbox':'[true,true]'}
when I am reading this data from the request.args in my python module.. I am able to get request.args['data'] which returns 'stringdata' but for the other keys like request.args['Email'] I am getting BAD REQUEST errors.
I have tried JSON.stringify the data separately for each item plus the whole data object but none of it is working.
I have also tried setting the data type and the contentType in the Ajax call but still no good.
$.ajax
({
url: '/abc',
data : {
"data": 'stringdata',
"Email": ['abc#example.com','def#example.com'] ,
"Hbeat":[true,true],
"Creport" : [true,true] ,
"Treport" : [true,true] ,
"Preport" : [true,true]
},
success: function(data)
{
},
complete: function()
{
}
});
Here the python part where I am trying to get the data.:
#app.route('/abc', methods=['POST','GET'])
def checkingdata():
print(request.args)
print(request.args['data'])
print(request.args['Email']) # this is where I am getting errors.
I expect to get the data as the form they are in. e.g. where I am passing the list of emails I need to get them as list. and where there are single string values I should get them as single string values.
thanks so much for your time. Please help if you can.
You need to use request.args.getlist:
emails = request.args.getlist('Email')
JSON stands for javascript object notation (as I'm sure you're aware), so why, when sending json via ajax do you need to turn it into a string to send it? Is it simply a formatting thing, or what?
This may belong in another place, if so, let me know, I'll close it and move it.
Obviously, I'm not looking for opinions, I'd like to know the actual answer.
Just to make sure I'm clear, I understand what JSON.stringify() does, and its counterpart JSON.parse(). I just want to know, why using stringify is required.
Thanks!
when sending json via ajax do you need to turn it into a string to send it?
If it isn't a string, then it isn't JSON in the first place.
JSON is a text based data format. HTTP is a text based communications protocol.
JSON stands for javascript object notation
JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.
AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.
When sending data to a web server, the data has to be a string.
That's why we are using JSON.stringify() function to convert data to string and send it via XHR request to the server.
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "submit.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Converting JSON data to string
var data = JSON.stringify({ "name": name.value, "email": email.value });
// Sending data with the request
xhr.send(data);
i have some questions that I want to ask, I building a web site and I send in ajax data and do decode and decode (js to php).
1) I want to ask why we should use in ajax encode and decode on json ?
2) what the json stringify do? I do it like this:
var data = JSON.stringify([category, amount, repeated, note]);
but I not realy understand why I should use this..my freind told me its not secure to send ajax without json encode, is it true?
First, AJAX is not tied to JSON but is the most used. You could use XML, yaml or you own format. On other hand, you always have sanitize and validate any data sent by the user. This is the real security risk.
Second, if you use a library as jQuery or AngularJs, you do not need stringify a javascript object (it is not the same as a JSON) the library does this for you.
// jQuery example
$.ajax({
url: '/save.php',
method: 'post',
data: {
id: 5,
name: 'pollin14'
}
};
// Save.php
$id = $_POST['id'];
$name = $_POST['name'];
Lastly, stringily transforms a javascript object to a javascript string. It is useful if you want to save a javascript object in a cookie, for example. Because a cookie only can save strings. Then when you retrieve the cookie you can use JSON.parse to get a javascript object.
I have to send the XML from the client side to the server side.
The method adopted by me was that:
First the xml is converted to string in the javascript and then post as a uri
var url = '/perl/set_zorder_xml.cgi'+'?'+xmlString+'&'+location+'&'+'nocache='+randomnumber;
xml string is the string that contains the xml in string form.
The post function looks like this:
if (window.XMLHttpRequest) {
req_anno = new XMLHttpRequest();
req_anno.open("POST", url, false);
req_anno.send();
}
The problem is that when my xml string is very large then html 414 error occurs i.e url too large.
Is there any way out, Javascript and perl is used
Even though you're doing a POST request, you're still sending the data in the querystring of the URL. Instead you should move the data to be sent as POST data, and remove it from the URL.
req_anno.open("POST", '/perl/set_zorder_xml.cgi', false);
req_anno.send('xml=' + encodeURIComponent(xmlString));
The XHR .send() method accepts the string to be sent as the request body (ie POST data).
i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.