I am using Java 1.7 and struts 1.3 framework. I am working for Japanese client. Currently my requirement is to send Search key (containing Japanese string) to the Action class using JQuery Ajax call. But at the action side I found some Japanese character are corrupted.
My code:
var searchKey = $('#searchtxt').val();
// some Japanese string value for search.
var data = {
// other properties
"searchKey": searchKey,
// Other properties
};
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (resultData){//dostuff}
});
I am quite new to SO I don't know how to format.
I have tried many solution on SO but not work for me. Any help will be appreciated.
Thank you for any help.
To solve this Japanese encoding problem, use URL Encoding mechanism and then send data through ajax call. And then at the Struts action side simply you need to decode it by using URL decoder mechanism.
It will solve this problem.
For the more clarity see the below code.
At the Java script side while fetching data from the hidden field use URL encoding method:
var searchKey = encodeURIComponent($('#searchtxt').val().trim());
// It will encode the Japanese string before send from Ajax call.
At the Struts Action side use URLDecoder class to decode the string value:
String searchKey=form.getSearchKey();
if(!searchKey.isEmpty()) //Check for empty or null string
{
// Decode the string using URLDecoder class from java.net package
form.setSearchKey(URLDecoder.decode(searchKey, "UTF-8"));
}
Related
When I make a POST request from JavaScript to my Django Rest Framework backend, my array of numbers is interpreted as string on the backend, causing this error:
cargo: ["Incorrect type. Expected pk value, received str."]
This is how I make the request in JavaScript:
const data = new FormData();
data.append("cargo", JSON.stringify([1, 2]));
fetch(url, {method: "POST", body: data}).then(//<more code>
In my Django Rest Framework serializer, I define the cargo field like this:
cargo = serializers.PrimaryKeyRelatedField(
many=True, queryset=models.CustomCargo.objects.all()
)
On the backend request.data.get('cargo') is the string "[1,2]". I need to use multipart/form-data because I'm posting a file too, so I can't use application/json, which does work. Is there a way to fix this in the JavaScript code (I'd rather not convert strings to integers on the backend)?
I ended up solving this by adding each item of the array to the FormData separately as strings:
[1, 2].forEach((cargo) => data.append("cargo", cargo.toString()));
If anybody has insight into why this works, please share.
I have a simple javascript / jquery AJAX request to submit a form to a php file for processing.
I want to send the parameters to the php file via GET.
If I send the parameters to the file using a manually encoded query string the processing works as expected.
An example of the query string is:
http://example.com/processor?param_1=Dogs¶m_2=Cats
As noted above, submitting this URL works OK.
When I make the same request using an AJAX call it fails.
If I dump the uri string sent by the AJAX call I see that it has added all the necessary parameters, but replaced & in the string with & - this change causes the call to fail (as the php file does not understand the query).
The query string sent to the AJAX call is:
http://example.com/processor?param_1=Dog¶m_2=Cats
I do not understand why the call is being made this way.
Any help with fixing would be most appreciated.
The AJAX call looks like this:
function submitEdit(first_param,second_param) {
$.ajax({
method: "GET",
url: "/content/edit",
data: {
param_1: first_param,
param_2: second_param
},
});
}
Thanks in advance for whatever insights you can offer.
I am sending an AJAX POST request using jQuery on a chrome extension but the data doesn't arrive as expected, accented characters turn out malformed.
The text "HÄGERSTEN" becomes "HÄGERSTEN".
The text appears fine in the console etc, only via AJAX to this other page it appears as mentioned. My AJAX call is basic, I send a data-object via jQuery $.ajax. I've tried both with and without contentType, UTF-8 and ISO-8859-1. No difference.
This is how I make my AJAX call:
var newValues = {name: 'HÄGERSTEN'}
$.ajax({
url: POST_URL,
type: 'POST',
data: newValues,
success: function() ...
});
The newValues object has more values but I retrieve them from a form. However, I have tried to specify these values manually as newValues['name'] = 'ÄÄÄÄ'; and still would cause the same problem.
The original form element of the page that I am sending the AJAX to contains attribute accept-charset="iso-8859-1". Maybe this matters.
The target website is using Servlet/2.5 JSP/2.1. Just incase it might make a difference.
I assume this is an encoding issue and as I've understood it should be because Chrome extensions require the script files to be UTF-8 encoded which probably conflicts with the website the plugin is running on and the target AJAX page (same website) which is using an ISO-8859-1 encoding, however I have no idea how to deal with it. I have tried several methods of decoding/encoding it to and from UTF-8 to ISO-8859-1 and other tricks with no success.
I have tried using encodeURIComponent on my values which only makes them show that way exactly on the form that displays the values I have sent via POST, as e.g. H%C3%84GERSTEN.
I have no access to the websites server and cannot tell you whether this is a problem from their side, however I would not suppose so.
UPDATE
Now I have understood POST data must be sent as UTF-8! So a conversion is not the issue?
Seems like the data is UTF-8 encoded when it is sent and not properly decoded on the server side. It has to be decoded on the server side. Test it out with the following encode and decode functions:
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
var encoded_string = encode_utf8("HÄGERSTEN");
var decoded_string = decode_utf8(encoded_string);
document.getElementById("encoded").innerText = encoded_string;
document.getElementById("decoded").innerText = decoded_string;
<div>
Encoded string: <span id="encoded"></span>
</div>
<div>
Decoded string: <span id="decoded"></span>
</div>
We too faced the same situation but in our case we always sent the parameters using JSON.stringify.
For this you have to make changes, 1) While making call to the page via AJAX you have to add content-type tag defining in which encoding data is sent
$.ajax
({
type: "POST",
url: POST_URL,
dataType: 'json',//In our case the datatype is JSON
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newValues),//I always use parameters to be sent in JSON format
EDIT
After reading your question more clearly I came to know that your server side JSP uses ISO-8859-1 encoding and reading some posts, I came to know that all POST method data will be transmitted using UTF-8 as mentioned.
POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard
But while reading post jquery-ignores-encoding-iso-8859-1 there was a workaround posted by iappwebdev which might be useful and help you,
$.ajax({
url: '...',
contentType: 'Content-type: text/plain; charset=iso-8859-1',
// This is the imporant part!!!
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
});
Above code is taken from Code Posted by iappwebdev
I don't know if it could have been solved using POST-data and AJAX. Perhaps if I made a pure JavaScript XHR AJAX call, I might be able to send POST-data encoded the way I like. I have no idea.
However, in my desperation I tried my final option (or what seemed like it); send the request as GET-data. I was lucky and the target page accepted GET-data.
Obviously the problem still persisted as I was sending data the same way, being UTF-8 encoded. So instead of sending the data as an object I parsed the data into a URL friendly string with my own function using escape, making sure they are ISO-8859-1 friendly (as encodeURIComponent encodes the URI as UTF-8 while escape encodes strings making them compatible with ISO-8859-1).
The simple function that cured my headaches:
function URLEncodeISO(values) {
var params = [];
for(var k in values) params[params.length] = escape(k) + '=' + escape(values[k]);
return params.join('&');
}
The client side character coding is not completely up to you (immagine the usage of the page from different users all around the world: chinese, italian...) while on the server side you need to handle the coding for your purposes.
So, the data in the Ajax-POST can continue to be UTF8-encoded, but in your server side you coan to do the following:
PHP:
$name = utf8_decode($_POST['name']);
JSP:
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
I'm working on a project and use ajax to update some informations in forms.
Here is my ajax function :
function update_ad() {
var project_name = document.getElementById("mol_project").value;
if (project_name !== '') {
$.ajax({
type: 'POST',
url: "controllers/get_project.php",
data: {project_name: project_name},
dataType: 'text',
success: function (data) {
var result = JSON.parse(data);
}
});
}
}
On my development environement everything works fine. The function get the json text from php server and parse it so I can use data after that.
But on my production environement, I receive a parsing error :
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is the received Json :
{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}
Jquery, apache and php version are the same on both environements. I guess it's a server configuration issue but I can't figure out where it is.
replace dataType: 'text' to dataType: json,
Look at the spec for JSON (easily understood version here: http://json.org/). There is nowhere that says that parenthesis are valid. ({"foo": true}), for example will never parse. It may be evaled as it is valid javascript, but javascript is not JSON.
Okay, in your JSON, there's a UTF-8 BOM in the front. Can you find the difference between:
{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}
And:
{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}
Where the latter is a valid JSON. Check it out with JSONLint. You need to make sure that the output you are receiving is free of UTF-8 BOM.
When I tried using the encodeURI() function on the JSON, it gave me this output:
encodeURI(' {"pr'); // "%20%EF%BB%BF%7B%22pr" - Wrong one!
encodeURI(' {"pr'); // "%20%7B%22pr" - Correct one!
We can make use of encodeURI to detect the anamolies and fix it in the client side. I am working on a solution.
The unicode signature, if you see, is EF BB BF, which is explained in this article. We can make use of this signature and try to correct it.
If you have the access to the PHP source, try setting the right headers:
header("Content-type: application/json; charset=utf-8");
please consider following snippet
i have submited a form which contains a background image url , i have serialize the form data . in php the URL is not decoding , how to get orignal url
$("#slider_settings_form").submit(function(e) {
var postData = $(this).serialize();
submited form
$.ajax({
url: ajaxurl,
data: {
"params": postData,
"action": "saveFormSettings"
},
method: "POST",
success: function(response) {
alert(response);
},
});
Use string urldecode( string $str ) function to decode your encoded URL data
for more follow this link
A successful parsing could be done by adding urldecode like this:
parse_str(urldecode($_REQUEST['params']), $params);
urldecode is important because it converts url encoded string into parsable string.
If you want to achieve it from javascript you can use these methods:
var uri = "http://stackoverflow.com/questions/30587877/how-to-decode-serialize-url-from-javascipt-in-php"
var uri_enc = encodeURIComponent(uri); //for encoding
var uri_dec = decodeURIComponent(uri_enc); //for decoding
Here is the link for more details:
Url decode and encode
Have a look at this related question.
We need to see how you're decoding the data in PHP to help you, but in addition to the answer ahead of mine (suggesting the use of urldecode), you should also make sure postData actually has data in it.
Only "successful controls" are serialized to the string [...] - second answer
It's entirely possible postData is nil. You should test it by alerting it and go from there. The question I linked to has a more thorough answer with code examples.
var postData = $(this).serialize(); -- this would create a query string like 'a=1&b=2', where a and b are form fields. You might want to fetch the value of a or b -- the following code will help you:
parse_str($_GET['params'], $params);
// then you can use $params['a'] to fetch form field 'a'
print_r($params);
// =>
//Array
//(
// [a] => 1
// [b] => 2
//)
For more about parse_str, see http://php.net/manual/en/function.parse-str.php