How do I use XMLHttpRequest.send()?
My code in JavaScript is as follows:
str_xml+="<xml_to_be_submitted><request_xml><client_id>"+document.frmCallEntryAdd.cboCLIENT.options[document.frmCallEntryAdd.cboCLIENT.selectedIndex].value+"</client_id></request_xml></xml_to_be_submitted>";
var obj_http=new ActiveXObject("Microsoft.XMLHTTP");
var str_url="ClientModuleFetch.aspx";
var str_http_method="post";
obj_http.open(str_http_method,str_url,false);
obj_http.SetRequestHeader("Content-Type","application/x-www-form-urlencoded");
obj_http.send(str_xml);
var str_reply=obj_http.ResponseText;
var xmlResponse = str_reply;
var objXmlDOM=new ActiveXObject("Microsoft.XMLDOM");
Can any body tell me what I am doing wrong?
For one, your method will only work in IE (I hope this isn't for a public website). A second error I can spot is that you've spelled SetRequestHeader with a capital S. It's supposed to be setRequestHeader.
Could you post exactly what error message (with the line number) you're getting, if any?
Your posted data is not application/x-www-form-urlencoded, which looks like this a=b&c=f.
Your posted data is either application/xml or text/xml which is generally not used with XMLHttpRequest unless you are manually constructing SOAP packets.
It is my guess that you are calling a script enabled service endpoint that can accept url encoded parameters so perhaps the manually constructed XML is not the appropriate data to post.
If not, you will need to explore the special corner of hades that is reserved for those who insist on calling SOAP from JavaScript. I do not envy you. ;-)
The return, on the other hand, possibly is XML that you will need to parse. I would suggest using a more cross browser compatible method for both XMLHttpRequest construction as well as XML parsing as your code seems to be IE centric.
Also, as noted elsewhere, you have a typo r.e. SetRequestHeaders should be setRequestHeaders.
Related
I very much appreciate anyone looking at this question and any helpful responses.
I am exploring the possibility of trying to load a text file from an external site to my site. The text file has been compressed or deflated with gzip, so the path looks like https://host/filename.txt.gz
I am trying to load the contents with a XMLHttpRequest, and then I am trying to decompress/inflate the contents using this https://github.com/augustl/js-inflate library. The response content-type is Application/Octet-stream.
So, my problem is that however the responseText is decoded, a lot of the characters produced are the "replacement character" (code 65533, or �). It is my understanding that this is produced when the decoder can't process the byte sequence.
The text files I am trying to decode/decompress are certainly valid, because if I download them they can be decompressed and viewed just fine.
var request = new XMLHttpRequest();
request.open('GET', 'https://host.something/filename.txt.gz');
request.onload = function() {
// the request text is all, there, looking like ��`�P GSE43615_non_normalized.txt t�I�,A�$���}���yXFf����D��...
var infwated = JSInflate.inflate(request.responseText); // (note: tried to base64decode the response first in case that's it. it doesn't seem to be)
// the 'inflated' result comes back as an empty string.
// As I debug the JSInflate library, it appears the the library is looking for bytes to signal how the text should be processed.
// The code breaks out of the processing in the first conditional because the byte is not recognized
console.log(infwated || 'failed'); // it's 'failed'
}
request.send();
I hope I explained this so it makes sense. So, my questions are:
Is what I am trying to do possible? (emphasis on possible, as opposed to reasonable)
If so, the vague question is, how can I read the response so it can be processed and decompressed? More specifically, how can text be 'read' in from an XMLHttpWebRequest in a way that an inflating algorithm can work with it?
Thanks a lot for any help!!!
Make sure you are using the correct responseType. "Text" is default, perhaps it should be "blob"?
I have the following XML as a string:
<battery_content>
<last_update>2012-15-09-22-40</last_update>
<total_downloads>234</total_downloads>
......
</battery_content>
I get the XML from an Ajax request and I store it in sXMLData. I do a quick window.alert(sXMLData) and everything's fine.
When I run the next code in IE8, it won't seem to work. Chrome and Firefox work.
window.alert("last_update" + $(sXMLData).find("last_update").text());
I can't seem to figure out why. Does this method not work with IE8? If so, how can I solve the problem?
The proper way to handle "XML as a dumb string" is to pass it through $.parseXML first:
window.alert(
"last_update" + $($.parseXML(sXMLData)).find("last_update").text());
However, you wouldn't need to do this manually if
either the server returns an XML Content-Type,
or the AJAX request you fetch the XML with uses the dataType AJAX option to specify that the response should be treated as XML
If the server is under your control, fix it to return the proper content type. If not, use the alternative solution. I recommend parsing the XML manually only if you are getting the string from third-party code that you have good reason to not want to touch.
I implemented this form submission method that uses xmlhttpreqeust. I saw the new html5 feature, FormData, that allows submission of files along with forms. Cool! However, there's a problem with accented characters, specifically those stupid smart quotes that Word makes (yes, I'm a little bias against those characters). I used to have it submit to a hidden iframe, the old school way, and I never had a problem with the variety of weird characters that was put in there. But I thought this would be better. It's turning out to be a bigger headache :-/
Let's look at the code. My javascript function (note the commented out line):
var xhr = new XMLHttpRequest();
var fd = new FormData(form);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.open($(form).attr('method'), $(form).attr('action'));
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
xhr.send(fd);
This is a shortened view, check out line 1510 at http://archive.cyark.org/sitemanager/sitemanager.js to view the entire function.
Then on the receiving php page, I have at the top:
header('Content-Type: text/html; charset=ISO-8859-1');
Followed by some basic php to build a string with the post data and submit it as an update to mysql.
So what do I do? If I uncomment the content-type setting in javascript it totally breaks the POST data in my php script. I don't know if the problem is in javascript, php or mysql. Any thoughts?
Encoding problems are sometimes hard to debug. In short the best solution is to literally use UTF8 as encoding everywhere. That is, every component of your application stack.
Your page seems to be delivered as ISO-LATIN-1 (sent via HTTP header from your webserver) which leads browsers to use latin1 or some Windows equivalent like windows-1252 even though you may have META elements in your HTML's HEAD telling user agents to use UTF8. The HTTP header takes precedence. Check the delivery of your other file formats (especially .js) to be UTF8 as well. If your problems are still appearing after configuring everything client side related (HTML, JS, XHR etc.) to use UTF8 you will have to start checking your server side for problems.
This may include such simple problems as PHP files not being proper UTF8 (very unlikely on linux servers I'd say) but usually consists of problems with mysql configurations (server and client), database and table default encoding (and collation) and the correct connection settings. Problems may also be caused by incorrect PHP ini or mbstring configuration settings.
Examples (not complete; using mysql here as a common database example):
MySQL configuration
[mysqld]
default_character_set = utf8
character_set_client = utf8
character_set_server = utf8
[client]
default_character_set = utf8
Please note, that those settings are different for mysql version 5.1 and 5.5 and may prevent the mysqld from starting when using the wrong variable. See http://dev.mysql.com/doc/refman//5.5/en/server-system-variables.html and http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html for details.
You may check your mysql variables via CLI:
mysql> SHOW VARIABLES LIKE '%char%';
Variable_name Value
character_set_client utf8
character_set_connection utf8
character_set_database utf8
character_set_filesystem binary
character_set_results utf8
character_set_server utf8
character_set_system utf8
When creating databases and tables try to use something like
CREATE DATABASE $db /*!40100 DEFAULT CHARACTER SET utf8 */
PHP.ini settings (should be the default already):
default_charset = "utf-8"
MB-String extension of PHP uses latin1 by default and should be reconfigured if used:
[mbstring]
mbstring.internal_encoding = UTF-8
mbstring.http_output = UTF-8
...some more perhaps...
Webserver settings (Apache used as example, applies to other servers as well):
# httpd.conf
AddDefaultCharset UTF-8
PHP source codes may use header settings like:
header('Content-type: text/html; charset=UTF-8');
Shell (bash) settings:
# ~/.profile
export LC_CTYPE=en_US.UTF-8
export LANG=en_US.UF-8
The above list is presented here just to give you a hint on what pitfalls may wait for you in certain situations. Every single component of your used web stack must be able to use UTF8 and should be configured correctly to do so. Nonetheless usually a simple correct HTTP header of UTF8 is enough to sort most problems out though. Good luck! :-)
Can I send a file as multipart by XMLHttpRequest to a servlet?
I am making a form and submitting it as multipart, but somehow I am not getting a response for successfully uploading it. I do not want the page to be refreshed, so it has to take place by Ajax.
That's only possible with the XHR FormData API (previously known being part of as "XHR2" or "XHR Level 2", currently known as "XHR Advanced Features").
Given this HTML,
<input type="file" id="myFileField" name="myFile" />
you can upload it as below:
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "myServletUrl");
xhr.send(formData);
XHR will take care about proper headers and request body encoding and the file will in this example be available on the server side as form-data part with the name myFile.
You need to keep in mind that FormData API is not supported in older browsers. At caniuse.com you can see that it's currently implemented in Chrome 7+, Firefox 3.5+, Safari 5+, Internet Explorer 10+ and Opera 12+.
In case you're using jQuery, then you might be tempted to use its $.val() function as below:
formData.append("myFile", $("#myFileField").val());
But this is incorrect as it doesn't return the whole File object, but merely the file name as String which is utterly useless as it doesn't contain the file contents.
If you don't want to use document.getElementById() for some reason, then use one of the following instead:
formData.append("myFile", $("#myFileField").prop("files")[0]);
formData.append("myFile", $("#myFileField")[0].files[0]);
An alternative is to use the jQuery Form plugin. Your entire form, when written and functioning properly without any line of JavaScript code, will then instantly be ajaxified with just the following line:
$("#formId").ajaxForm(function(response) {
// Handle Ajax response here.
});
It also supports file uploads as well by a hidden iframe trick. See also this jQuery Form documentation for an in-depth explanation. You may only need to change the servlet code to be able to intercept on both normal (synchronous) and Ajax (asynchronous) requests. See also this answer for a concrete example: Simple calculator with JSP/Servlet and Ajax
Either way, the uploaded file should then be available in the doPost() method of a #MultipartConfig servlet as follows:
Part myFile = request.getPart("myFile");
Or if you're still on Servlet 2.5 or older, use Apache Commons FileUpload the usual way. See also this answer for a concrete example: How can I upload files to a server using JSP/Servlet?
It's not possible to send multipart/form-data with XMLHttpRequest (though it is possible in modern browsers, with XHR2. See BalusC's answer).
A common way to achieve what you want is to use a regular form, but in an iframe instead. This way, only the iframe is refreshed on upload.
I work on a website which is all done in iso-8859-1 encoding using old ASP 3.0. I use Yahoo YQL to request data (XML) from external websites but which I request to be returned as JSON-P (JSON with a callback function so I can retrieve the data).
The problem I am facing is that YQL seems to always return data encoded in utf-8, which is bad for me when I try to display any textual data retrieved from that query. Characters like é, à, ô, get gibberished in IE6 & IE7 since the encoding does not match.
Anyone knows how to convert utf-8 data retrieved via JSON-P with YQL to iso-8859-1 and be displayed correctly ?
I already tried that solution, but it does not work. Server side functions are not an option too, ASP 3.0 does not include function such as utf8_decode.
Thank you
I have no idea whether this will work, but here's something you can try if you want.
A <script> tag can have a charset attribute specified when referencing a remote JS file. See the theory here. This definitely works for content that is stored inside the JavaScript file and e.g. output using document.write.
Whether the implicit conversion works for data fetched by a routine defined in that file through JSONP? I have no idea. My guess is, probably not. I can't test it right now but if you do, I'd be very interested in the outcome.