I have a website which apperently removes the correct encoding (ISO-8859-1) from a string and sends it wrong.
I have this encoding specified in my HTML
<meta charset="ISO-8859-1">
I load my javascript via
<script type="text/javascript" charset="ISO-8859-1" src="...
I send for Information via JQuery Ajax Request like this (with german special character 'ö' and 'ä'):
$.ajax({
url: '..',
type: 'POST',
contentType: 'application/xml;charset=ISO-8859-1',
data: xmlRequest.html(),...
This is translated into a request and in the chrome developer tools I see this in the Request Header:
..
Content-Type: application/xml;charset=UTF-8
..
What happened there?
Of course the special characters are encoded wrong ("ö" instead of "ö") the server can't understand me and i get an error.
Because I had the same problem, I'll provide a solution that worked for me. Background: Microsoft Excel is too stupid to export a CSV-File in charset UTF-8:
$.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');
}
});
According to the jQuery.ajax() contentType documentation:
Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side."
Related
I am trying to pass the value of a textarea to an php page to then be processed and added to a SQL database.
I want the text area to be able to support special characters.
Everything works fine till I put this string in the text area and post it:
JΛ̊KE#2##&($^#%###%))$&#("""
I am getting a 501 Not implemented error.
Now when I paste in certain PHP code into the text area (not to run, purely to save as a string), I get a 403 Forbidden error.
Why does the value of the text area affect the error code?
For now, the paste.php file has no code so that I could try and understand where the error is coming from. I am certain the error is coming from the ajax post. I've looked everywhere online but have not been able to find how to make the string safe to post. encodeURIComponent doesn't seem to work in this case.
Here is the JS for the button press:
var note = $("#note").val();
var dataString = encodeURIComponent(note);
$.ajax({
type: "POST",
url: "php/paste.php",
data: JSON.stringify({
paste: dataString
}),
dataType: 'text',
contentType: "application/json; charset=utf-8",
success: function(msg) {
alert(msg);
console.log(msg)
},
error: function(ts) {
alert(ts.responseText)
}
});
try adding this
Content-Type: application/x-www-form-urlencoded
What was needed was to use this function on the data.
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
Change the content type to
ContentType: "application/x-www-form-urlencoded; charset=UTF-8"
and for the kicker, add this to my .htaccess file :
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
$.ajax({
url: Settings.get('serverURL') + 'PlaylistItem/CreateMultiple',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newItems)
});
I'm explicitly setting the contentType of the AJAX request to indicate JSON is being sent across the wire. However, I seem to be inconsistent in my application of contentType across my code and all AJAX requests are working properly.
Is it necessary or beneficial to be explicit with the JSON contentType or should I omit it?
According to the JQuery documentation
contentType (default: 'application/x-www-form-urlencoded;
charset=UTF-8') Type: String When sending data to the server, use this
content type. Default is "application/x-www-form-urlencoded;
charset=UTF-8", which is fine for most cases. If you explicitly pass
in a content-type to $.ajax(), then it is always sent to the server
(even if no data is sent). The W3C XMLHttpRequest specification
dictates that the charset is always UTF-8; specifying another charset
will not force the browser to change the encoding.
In practice I have found it beneficial to explicitly state it either in $.ajax or through
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
as application/x-www-form-urlencoded has caused me the occasional null value in MVC action parameters as per this article
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx/
I have xml data fetched from a file on the server side, successfully accessed without use of server-side scripts (e.g. no php).
I'd like to write that xml data back to the file on the server side after some minor changes, again without use of server-side scripts (e.g. no php). Here is what I have so far:
<button id='WriteToXml'>Write to XML</button>
<script>
$('#WriteToXml').click(function () {
var output_xml;
$.ajax({
type: "GET",
url: "/data/testdata_input.xml",
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find('input').remove();
$(xml).find('test').append('<output></output>');
output_xml = xml;
}
});
// Alternative code?
// $.post( "/data/testdata_output.xml", $(output_xml), "xml" );
$.ajax({
type: 'POST',
url: "/data/testdata_output.xml", //url of receiver file on server
data: $(output_xml) , //your data
contentType: "text/xml",
dataType: "xml",
cache: false,
async: false,
success: function(xml) {console.log( 'success\n'+ $(xml).find('test') );}
});
});
</script>
In another SO thread, I read that it was necessary to use a server-side script due to the design of javascript (for security reasons). But then in another thread, I saw code that didn't involve php, so I'm hoping I could use that code to write to the xml file on the server:
$.ajax({
type: 'POST',
url: "/data/testdata_output.xml", //url of receiver file on server
data: "<test></test>" , //your data
contentType: "text/xml",
dataType: "xml",
cache: false,
async: false,
success: function(xml) {console.log( 'success\n'+ $(xml).find('test')
So far I get a success message, but the xml file on the server remains intact. It would be great to understand where I misunderstood. In the meantime I will use this php code on the server-side and try to have it work:
//javascript
$.post('savedata.php', {data: "<test></test>",filename: "/data/testdata_output.xml"}, function(){/*Save complete*/});
//savedata.php
$data = $_POST['data'];
$filename = $_POST['filename'];
$f = fopen($filename, 'w+');
fwrite($f, $data);
fclose($f);
But it would still be nice to understand.
Also, I'd love some notes on using xml file types in the $.post code rather than a php file (based on the $.post jquery doc):
$.post( "/data/testdata_output.xml", "<test></test>", "xml" );
Thanks
You need a server side script to handle anything that modifies the server. That script should set out the restrictions on who is allowed to write what and where. It's not due to the design of javascript; it's just that otherwise, anyone could write any file to any web server, which is clearly unsafe.
When the URL of the request is a script that responds to user input, you'd use an HTTP POST. When the URL of the request represents a file to be written (as in your case), you would typically use an HTTP PUT. (You don't really have to use PUT -- you're the one writing the handler script, after all -- but writing to a file on the server is what PUT is for.)
In terms of the jquery request, without server-side scripting, the POST request is not significantly different from a GET request, in that the content of the file found at the URL is returned as the body of the response. (There are differences -- e.g. the POST would not be cached -- but I think that's the gist of the jquery example you mention.)
I need to send data to the server using the character set Big-5, however the browser seems to only encode the data in UTF-8. If I were to make a form, then it can be achieveable with the following attribute:
<form accept-charset="Big5">
However, I want to send the data through XHR. Some answers suggest that contentType can let me change it. But according to jQuery's documentation, the encoding cannot be overridden: (at least this is true in Chrome.)
The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
$.ajax({
url: "dummy url",
type: "GET",
data: {
q: "Test"
},
contentType: "application/x-www-form-urlencoded;charset=Big5"
}, function(){});
//This won't work.
Is there any way to get around it?
For example, suppose I'm using AJAX to send a request to a server like so:
$.ajax(
{
url: url,
beforeSend: function (request) { request.setRequestHeader('X-Test', 'one'); },
});
The documentation for $.ajax contains the following:
contentType (default: 'application/x-www-form-urlencoded;
charset=UTF-8') Type: String
When sending data to the server, use this
content type. Default is "application/x-www-form-urlencoded;
charset=UTF-8", which is fine for most cases. If you explicitly pass
in a content-type to $.ajax(), then it is always sent to the server
(even if no data is sent). The W3C XMLHttpRequest specification
dictates that the charset is always UTF-8; specifying another charset
will not force the browser to change the encoding.
According to this, the default is UTF-8, but I'm not clear from the description if the contentType header affects only the encoding of the request's body or the encoding of the other headers as well (if the latter can even be changed).
contentType only affects the body/document.
According to this you can use any ISO-8859-1 characters in the header.
You have to remember that AJAX render part of the HTML body, so when you send data in a AJAX request with some content type, for example iso-8859-1, the data is setting with that content type only in the AJAX request life cycle.
I hope my answer be useful for you.
Good lucky.