I have a text file with the character set as "Shift_JIS" and the file contains Japanese characters. And then I do ajax request to that file as shown below.
$.ajax({
url: "demo.txt",
success: function(result){
alert(result);
}}
);
But the data that is shown in alert is not valid Japanese character. Instead it shows some junk data. Even though I tried to set the response header character set and I do many of the solution that is already before in stackoverflow, But it didn't work. Can any one help me to solve this ?
Note: Browser is Internet Explorer
You said you tried to change the charset, have you tried changing the contentType to plain text ? :
$.ajax({
/*...*/
contentType: "text/plain; charset=Shift_JIS"
/*...*/
})
You cannot read a Shift_JIS file into a string object directly in JavaScript. You have to once store the content of the file into a binary object and then decode it into UTF-16 (the internal representation of JavaScript string) with TextDecoder.
Unfortunately, jQuery's $.ajax() cannot handle the response body as binary (dataType: 'binary') out of the box. So you have to use additional module like
jQuery BinaryTransport, or use XMLHttpRequest like this:
// ref. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
var oReq = new XMLHttpRequest();
oReq.open("GET", "demo.txt", true);
oReq.responseType = "arraybuffer"; // handle response body as binary
oReq.onload = function (oEvent) {
if (oReq.response) {
var sjisDecoder = new TextDecoder('shift-jis');
alert(sjisDecoder.decode(oReq.response)) // Note: not oReq.responseText
}
};
oReq.send(null);
Related
Issue : While uploading large image files i recognized that while uploading on my AWS server having 1gb memory uses it's full capacity, it goes upto 932 mb usage which causes crash to the process. I was saving that image in the form of DataURI and then I read somewhere that saving it in the form of blob can solve my problem. So i want to append that blob to formData and send to server and this is the reason i come up with this question. However if any else suggestion regarding the same problem to save image more efficient way when memory is concerned, will be appreciated.
Motive
I want to send an image to the server side as in the form of a blob.
What I have done
I am currently having a dataURI which I have converted into a blob. Further, i append that blob to formData and try to send it to server side/php using ajax.
JAVASCRIPT:
function convertURIToImageData(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
//
const dataURIconverter = () =>{
let img;
var image = new Image();
image.crossOrigin = 'anonymous'; // cross domain
// create an empty canvas element
var canvas = document.createElement("canvas"),
canvasContext = canvas.getContext("2d");
image.onload = function () {
//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;
// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);
// get canvas contents as a data URL (returns png format by default)
var dataURL = canvas.toDataURL();
// console.log(dataURL)
let blob = convertURIToImageData(dataURL)
console.log(blob)
var formData = new FormData();
formData.append('blobImage',blob)
$.ajax({
type: 'POST',
url: 'check.php',
data: formData,
processData: false
}).done(function(data) {
console.log(data);
})
}
image.src = "https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg"
}
dataURIconverter()
PHP
<?php
var_dump($_POST['blobImage'])
var_dump($_POST);
//var_dump($_FILES['image']);
//$name = $_FILES['image']['tmp_name'];
//echo $name;
//echo $_FILES['image']['tmp_name'];
//$status = move_uploaded_file($name, $_FILES['image']['name']);
//echo 'successfully stored at '.$_SERVER['HTTP_HOST'];
?>
Error
I am receiving null as in console and i also checked the headers where i see formData with the name
As you can see, $_POST showing the blob but $_POST['blobImage'] is showing null.
Solution I require:
i am not that quick to php so i am not sure if i am sending the blob in the right way or receiving it.
I have provided my all possible efforts i have taken to achieve my motive.
Thanks to the community for help.
Add the following three properties on your jQuery Ajax call , they are required for blobs :
cache: false,
contentType: false,
processData: false
Then do not use formData in the data property of your Ajax Call , you simply need to add your created blob.
Also add a small rendering callback (apart from the console.log you already use) to print the Image. Your AJAX call gets like this :
$.ajax({
type: 'POST',
url: 'check.php',
data: blob,
cache: false,
contentType: false,
processData: false
}).done(function(data) {
document.write("<img src='"+data+"'></img>");
})
Change your PHP code to the following :
<?php
$res = file_get_contents("php://input");
echo "data:image/jpg;base64,".base64_encode($res);
?>
As far as the "php://input" use is concerned. It returns all the raw data that come after the headers of your request and it does not care what type they are which is pretty handy in most cases. Whereas $_POST will only wrap the data that have been passed with the following Content-Types :
application/x-www-form-urlencoded
multipart/form-data
If you really want to use FormData then you can change the request to the following :
$.ajax({
type: 'POST',
url: 'check.php',
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function(data) {
console.log(data);
})
And you should also change your PHP file to get the $_FILE. Sending data this way , the Content-Type of the Request will be "multipart/form-data" which will have blobs , images and generally files on the $_FILES and the rest on the $_POST so the "php://input" will not be helpful.
<?php
var_dump($_FILES);
?>
Also keep in mind that when uploading blobs this way , they will get a random name , if you are not going to be generating filenames on the Server-Side (which you probably should in most cases) and want a specific name designated by the uploader , then you can pass it along with the FormData like :
formData.append('blobImage',blob, "MyBloBName");
If you set contentType: false in your jQuery Ajax call , you can still use the same code with formData and then access the file on the server through $_FILES['blobImage']
The problem is that $_REQUEST, and therefore $_GET and $_POST objects have a limitation to the number of characters available to them.
post_max_size
in PHP.ini controls the maximum size of post.
Browsers and their implementations of $_GET control the limit of a $_GET request. As it appears in their URL bar. For example IE9's limit is 2000 characters so if your blob ends up as anything more than 2000 characters in the $_GET Request. The general consensus is that $_GET requests should be much less than 255 bytes. And if you approach this limit be careful because older browsers and protocols are completely unprepared for this.
I am trying to make an XHR with JavaScript, but I can't get it to work correctly.
When I see the right requests in the "Network" tab of the Chrome developer tools I see that they have a "Form Data" section where are listed all the informations sent with the request, like this:
Now, I've tried making my XMLHttpRequest in any way I know, but I can't get that result.
I have tried this:
var xhr = new XMLHttpRequest(),
form_data = "data%5Btumblelog%5D=drunknight&data%5Bsource%5D=FOLLOW_SOURCE_REBLOG";
// this is uri encoded: %5b = [ and %5D = ]
xhr.open('POST','https://www.somesite.com/page?' + form_data, false);
xhr.send();
But I got this "Query String Parameters" instead of "Form Data":
I have also tried this:
var xhr = new XMLHttpRequest(),
formData = new FormData();
formData.append("data[tumblelog]", "drunknight");
formData.append("data[source]", "FOLLOW_SOURCE_REBLOG");
xhr.open('POST','https://www.somesite.com/page', false);
xhr.send(formData);
But I got this "Request Payload" instead of "Form Data":
And, finally, I have tried this:
var xhr = new XMLHttpRequest(),
formData = {
"data[tumblelog]": "drunknight",
"data[source]": "FOLLOW_SOURCE_REBLOG"
};
xhr.open('POST','https://www.somesite.com/page', false);
xhr.send(JSON.stringify(formData));
But I got another "Request Payload" instead of "Form Data":
Now, my question is: how can I send my XMLHttpRequest in order to obtain the same result as shown in the FIRST image?
You're missing the Content-Type header to specify that your data is form-like encoded.
This will work:
var xhr = new XMLHttpRequest(),
data = "data%5Btumblelog%5D=drunknight&data%5Bsource%5D=FOLLOW_SOURCE_REBLOG";
xhr.open('POST','https://www.somesite.com/page', false);
// LINE ADDED
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
EDIT
FormData is generally used to send binary data and will automatically set the Content-Type header to multipart/form-data (see FormData Spec and FormData Examples). However you have to make sure the server also accepts request using this MIME-type, which apparently is not your case, as you already tried and it didn't work.
I noticed the OP tried using FormData in one of their iterations to solve the original problem.
I've recently started using the Fetch api for sending form data. It's designed with promises making it really easy to use (especially if there's a form to leverage for all of the inputs):
var form = document.forms[0];
var data = new FormData(form);
fetch(form.action, { method: form.method, body: data })
.then((response) => {
// handle response
}).catch((error) => {
// handle error
);
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Posting this as an answer because I believe it will give you exactly what you want to know;
I just want to know what sort of method is used to send that kind of data. I can assure you that the first image is obtained using an XHR
You haven't given enough information for us to see how the "correct" version is generated, but you can capture the relevant bits you want, drop in code like this before the working XMLHttpRequest is .opened;
(function (obj, methods) {
var i;
function log() {
console.log.apply(console, arguments);
}
for (i = 0; i < methods.length; ++i)
obj[methods[i]] = (function (method_name, method) {
return function () {
log.call(null, method_name, arguments);
return method.apply(this, arguments);
}
}(methods[i], obj[methods[i]]));
}(XMLHttpRequest.prototype, ['open', 'send', 'setRequestHeader']));
Now perform the action to make it fire and the relevant parameters will be logged so you can see exactly what happens to it as it is set up and sent, which should allow you to know what to pass into your one.
The problem is that I get a forbidden (403)
I'm going to assume this is not a same origin security-error because this looks server-returned and not a browser-initiated abort
I'm very new at this. I've read books to learn javascript and HTML, so unfortunately I haven't learn much about this.
I never used AJAX before, so not sure how it works, searched online, but find all examples too complicated.
Basically what I want to do is save a playlist (although not with cookies). Something everyone can see and add-on to it (similarly to a comments section).
This is just an example, I'm doing something else, but the html + js would be a bit big. Just want to know how I would do it on this, so that I could understand it (hopefully) and apply it elsewhere.
This would be the body and below it the code I have (currently all my code is in [head]):
<body>
<form>
<input type="text" id="songInput" size="40" placeholder="Song Name">
<img id="addButton" src="button.png">
</form>
<ul id="playlist"></ul>
</body>
<script>
window.onload = load;
function load() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
function buttonClick() {
var text = document.getElementById("songInput");
var song = text.value;
var button = document.getElementById("addButton");
var add = document.createElement("li");
add.innerHTML = song;
var ul = document.getElementById("playlist");
ul.appendChild(add);
}
</script>
First you have to understand what AJAX is. AJAX is not a "tool" that you can use, instead, it's a name for the techniques (asynchronous JavaScript + XML). Basically it means "getting/posting data from/to server."
In vallina JavaScript, XMLHttpRequest lets you send and receive data to and from a server:
var xhr = new XMLHttpRequest(); //Create an XMLHttpRequest object
xhr.open('get', url); //Set the type and URL
xhr.onreadystatechange = function(){ //Tell it what to do with the data when state
// changes
if(xhr.readyState === 4){ //4 is the code for "finished"
if(xhr.status === 200){ //Code 200 means "OK"
//success
var data = xhr.responseText; //Your data
}else{
//error //Deal with errors here
}
}
};
xhr.send(null); //After finished setting everything, send the
// request. null here means we are not send-
// ing anything to the server
It might look complicated, and xhr is repeated quite a lot. Not to mention the problems that we have to deal with when executing in IE.
There is solution for that. We will use libraries to simplify the process and let it do the hard works for us.
In jQuery, this is what you have to do to for a basic XMLHttpRequest:
$.ajax({
url: url,
data: { /*data here*/ },
type: /*"GET" or "POST"*/
}).done(function(data){
//success
}).fail(function(){
//error
});
//Not complicated at all with jQuery
Since AJAX is a group of techniques to send/receive data, there're more ways to do the "same" thing. You might realize the code above only works for URL that has the same domain (pages on your server). To bypass that limitation, there's another technique called JSONP. Sounds fancy, but what it means is simply "using the <script> tag to get pass that limitation". And of course, jQuery got you covered:
$.ajax({
url: url,
data: { /*data here*/ },
type: /*"GET" or "POST"*/,
dataType: "JSONP" //specifying dataType to be JSONP
}).done(function(data){
//success
});
Here is a simple example of getting content off Wikipedia using JSONP: http://jsfiddle.net/DerekL/dp8vtjvt/
With a normal XMLHttpRequest call to Wikipedia's server would not work. However by exploiting the fact that script tags are not restricted by the Same-Origin Policy we can achieve the same thing. Note that for JSONP to work, the server must be programmed internally to allow returning a JSON with wrapped callback call.
I'm having some problems posting data from a web page, using jQuery, to a servlet. While I'm an experienced Java developer, I'm very new to javascript/jQuery/servlets. I'm using Eclipse, Apache Tomcat, and Chrome.
I have an XML file (from 6KB to 30MB in size) that I wish to load into the browser, modify, then post to the servlet.
My HTML has:
<input id="filechooser" type="file" onchange="readFile()">
My JS has:
var file = document.getElementById('filechooser').files[0];
var reader;
reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = loaded;
function loaded(evt){
var result = evt.target.result;
var xml = $(result);
...
[make modifications to xml]
}
Some jQuery code that I use in modifying the xml are $(xml).find("NODE").val() and $(xml).find("OTHER_NODE").attr("attribute-name","newValue")
I now need to post that xml to a URL, where it will be used to process some information. In the Chrome console, I can view the content of the xml object:
> xml
[<!--?xml version="1.0" encoding="ISO-8859-1"?-->,#text,
<root_element>...</root_element>]
> $(xml)
[<!--?xml version="1.0" encoding="ISO-8859-1"?-->,#text,
<root_element>...</root_element>]
> console.dir(xml)
jQuery.fn.jQuery.init[3]
0: #comment
1: #text
2: root_element
length: 3
__proto__: Object[0]
My servlet is empty so far:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post");
}
I created a button that executes some javascript. The following two code snippets both post to the server:
$.post("http://localhost:8080/MyWebApp/MyWebAppUrl", xml);
and:
$.ajax({
type: "POST",
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml
});
My problem is, I don't know if I'm sending my XML correctly, or how to properly consume it. What do I need to do to my jQuery code to post it correctly? How do I get it out of my HttpServletRequest? If I can get the xml text as a String, I know exactly how to manipulate it in Java, and get it to do whatever I want.
After 10+ hours searching the web, I still can't find the answer. I'm sure it's out there, but I can't seem to connect the dots.
UPDATE:
epascarello was spot on for posting an XML document. However, I was parsing the document incorrectly.
Notice that I read the file, then stored the result var xml = $(result). The file was read as a text string, and I was converting it to an HTML document.
What I needed to do was var xml = jQuery.parseXML(result). That way, I didn't have to convert it back to a text string, and tag capitalizing is maintained.
Note that maintaining capitalization is of critical important.
Set the content type
$.ajax({
type: "POST",
contentType: "application/xml", //or text/xml?
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml
});
Add processData: false to your call and it should leave the string alone...
$.ajax({
type: "POST",
contentType: "application/xml", //or text/xml?
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml,
processData: false
});
I have the following script
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/getSelectedProductData?offerCollectionRef=" + offerCollectionRef + "&brandRef=" + brandRef + "&priceRef=" + priceRef + "&defaultSmallImage=" + defaultSmallImage + "&offerCode=" + offerCode + "&index=" + index, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
I know how to write a $.ajax in jQuery. But I am stuck at how to send data.
My questions are
The return is XML and so the dataType: xml. am I correct?
How should I pass the data to the url?
Please elaborate on these things.
Disclaimer: The thing is that I couldn't test it myself and so this question.
1 The return is XML and so the dataType: xml. am I correct?
You actually don;t need to specify it if the server sets proper Content-Type header to text/xml. jQuery will automatically consider the result as XML
2 How should I pass the data to the url?
You could use the data hash:
$.ajax({
url: '/getSelectedProductData',
type: 'GET',
dataType: 'xml', // not necessary if the server sets the Content-Type: text/xml response header
data: {
offerCollectionRef: offerCollectionRef,
brandRef: brandRef,
priceRef: priceRef,
defaultSmallImage: defaultSmallImage,
offerCode: offerCode,
index: index
},
success: function(xml) {
// ...
}
});
Also you seem to be sending a synchronous request by setting the async parameter to false. To emulate the same with jQuery you could add the async: false option. This being said, you probably shouldn't be doing it. SJAX (sync javascript) will block the browser during the request and ruin the user experience.
Yep.
You can use the data property when passing settings to $.ajax(). It can be an object (it will be converted to a query string) or a query string. Please check the jQuery Manual for further details.
Excerpt from the manual:
data (Object, String) Data to be sent to the server. It is
converted to a query string, if not already a string. It's appended to
the url for GET-requests. See processData option to prevent this
automatic processing. Object must be Key/Value pairs. If value is an
Array, jQuery serializes multiple values with same key based on the
value of the traditional setting (described below).
So from your example, url shall be '/getSelectedProductData', and data could be everything after ?. Or you can organize them into an object like { 'offerCollectionRef': offerCollectionRef, ... }, it is a bit more readable.