Convert xhr ajax call to xdr for IE8 - javascript

I have asp web page responsible of uploading file using ajax.
the html code of the form is:
<form method="post" action="ajax/firmwareUpload" enctype="multipart/form-data" id="uploadform" name="uploadform">
<div class="left">
<span id="lang502009" title="502009">Firmware File</span>:
<input name="download image file" id="uploadfilename" type="file">
</div>
<div class="right">
<div class="upload" id="uploadManual">
<input type="submit" class="button button-blank" value="Upload"/>
</div>
</div>
</form>
the ajax code is :
$("#uploadform").submit(function(e) {
$.ajax({
url: 'ajax/firmwareUpload',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
enctype: 'multipart/form-data',
success: function(data) {
if (data.error) {
$("body").load("subpage/upgradefail.asp");
setTimeout(backToIndex, 5*1000);
}
else {
var time = data.return;
$("body").load("subpage/upgradewait.asp");
setTimeout(backToIndex, time*1000);
}
},
error: function(data) {
alert("Operation could not be completed");
}
});
e.preventDefault();
});
This code works well as wanted for different browsers like firefox, chrome, safari, Opera. but I got problems with IE8 in the ajax response.
But the request works fine and can receive from the browser and send to the browser the response. But when IE8 receives the response it can't access to the success or error functions.
After a lot of searches I found in the internet that the problem is because IE8 have some problems with xhr communication. And the ajax code can be better with xdr.
My problem here is how I can convert my ajax code to xdr?
The problem especially is with processData, enctypes attributes and "new new FormData(this)". and is there modification that should be done in the tag form attributes?

Related

How to avoid move_uploaded_file() refresh the page on button click

I am using $.ajax({}) of jQuery, I am trying to move the uploaded file in folder on click. The upload came successful but my problem is when uploading, the page is refreshing I already tried e.preventDefault() and <button type="button">
This is my html code
<input type="file" id="student-img-file" accept="image/*" name="student-img-file">
<button type="button" id="btn-submit-form" class="mt-4">Submit Form</button>
This is my jQuery code
$('button#btn-submit-form').on('click', function(e){
let formData = new FormData()
formData.append('student-img-data', $('#student-img-file').prop('files')[0])
$.ajax({
url: '../PHPFunctions/AdmissionFormFunction.php',
method: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(result){
console.log(result)
}
})
})
this is my PHP(AdmissionFormFunction.php) code
$studentImgData = $_FILES['student-img-data'];
if(move_uploaded_file($studentImgData['tmp_name'], '../FileUploads/' . $studentImgData['name'])){
echo "YESSSSSSSSSSSS";
}
I am not using form tags by the way
I just turned off my vs code live server. I forgot that any changes that i've made in my folder system in vs code will refresh the page.

JQuery toggle() - Element only displayed after JQuery submit function

I'm trying to display a loading gif at the beginning of a JQuery submit function, but the gif is only displayed after the submit function ends. (Each of the alerts are displayed before the gif)
For the ajax, I currently set it to always respond with an error saying "No video chosen".
JQuery
$("#myForm").submit(function(e){
e.preventDefault();
$("#loading_gif").toggle();
alert('The gif should be displayed');
var Fdata = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "/send_video",
data: Fdata,
processData:false,
contentType: false,
async:false,
cache: false,
success: function(data){
alert('success');
//commented or else the gif is never displayed
//$("#loading_gif").toggle();
},
error: function(error){
alert('error');
e = document.getElementById("error");
e.innerHTML = JSON.parse(error.responseText);
//commented or else the gif is never displayed
//$("#loading_gif").toggle();
}
});
});
HTML
<div id="error"></div>
<form id="myForm" action="/" method="post" enctype="multipart/form-data">
<input id="video" type="file" name="video">
<input id="submit" type="submit" value="Send">
<img id="loading_gif" style="display:none" src="mysite/img/loading.gif">
</form>
I don't think $.ajax is the problem, because I removed it and still didn't work.
I already tried to separate toggle() from the rest of the submit by doing this:
$("#submit").click(function(){
$("#loading_gif").toggle();
$("#myForm").submit();
});
But it changed nothing.
Thanks a lot.
You don't want async:false remove this and your problem should go away.

Accessing type="file" input from POST method on server side

Having some difficulty understanding how to access type="file" input on the server side. Below is the code I'm using. I use AJAX because I want my web app to not require refreshing, and am using a slightly roundabout way of submitting my form so I can have a better UI.
My HTML:
<form id="updateProfileImageForm" enctype="multipart/form-data">
<div class="updateProfileImageContainer">
<img src="images/profile/generic.png" class="updateProfileImage">
<div class="updateProfileImageOverlay" onclick="changeImageToUpload()">
<div class="updateProfileImageOverlayText">Upload new image</div>
</div>
<input type="file" id="imageToUpload" name="image" style="display: none;" onChange="$(this).closest('form').trigger('submit');"></input>
</div>
</form>
My JS:
function changeImageToUpload() {
$('#imageToUpload').trigger('click');
}
$('#updateProfileImageForm').submit(function(e) {
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/changeProfile',
data: form_data,
processData: false,
success: function(response) {
if(response.message != null) {
alert(response.message);
} else {
// Change profile image displayed
$('.updateProfileImage').attr("src", response.newProfileImage);
alert('Profile picture successfully updated! Refresh your browser to update your window!');
}
}
})
});
My Server PHP:
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
}
Var_dump on $_FILES shows an empty array, while var_dump on $_POST shows a lot of information (which I'm assuming is my data file). However, accessing the 'image' property on either $_POST or $_FILES (through either $_POST['image'] or $_FILES['image']) gives me either "undefined index" or "undefined variable".
Would you guys be so kind as to educate me on:
What's the difference between $_POST and $_FILES?
How should I be accessing the file in this case?
Thanks!
You're missing a necessary config option in your ajax request, you need to set contentType to false
$.ajax({
type: 'POST',
url: '/changeProfile',
data: form_data,
processData: false,
contentType: false,
success: function(response) {
if(response.message != null) {
alert(response.message);
} else {
// Change profile image displayed
$('.updateProfileImage').attr("src", response.newProfileImage);
alert('Profile picture successfully updated! Refresh your browser to update your window!');
}
}
})
jQuery.ajax sets the content type by default to application/x-www-form-urlencoded which is incorrect for your FormData object, if you set it to false it will be set correctly by the underlying XMLHTTTPRequest object.
Idea behind it.
Instead of using file as post to PHP, simply convert image to base64 and receive that string using ajax in php.
Refer to this URL

how to upload file and save to directory? [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 6 years ago.
HTML
<div style="width:200px">
<form action="javascript:_bulkUser();" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form>
</div>
js(ajax call)
_bulkUser : function(scope) {
try {
$.ajax({
type : "post",
url : "FileUploadServlet",
success : function(data) {
alert('Sucess');
},
error : function(data) {
console.log(data);
}
});
} catch (e) {
console.log(e);
}
}
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("working");
MultipartRequest mp = new MultipartRequest(request, "e:/new");
out.print("successfully uploaded");
}
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing such as jQuery Form plugin (example here).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JS disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's with help of jQuery Form plugin just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How to upload files to server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals to XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JS disabled (as of now, it are mostly the older mobile browsers which have JS disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return ajax response (e.g. write JSON or XML).
} else {
// Return regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 File Upload to Java Servlet and sending a file as multipart through xmlHttpRequest.
This code also works fine for me :
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>

Jquery ajax long polling error- Chrome

I am just trying ajax long polling for a simple chat application. Here is the js code. Its works well in Firefox, But when it comes to chrome, the appended text is repeated. I cant figure out what the error is.
$(document).ready(function(){
$('#chatText').keydown(function(event)
{
if (event.keyCode == 13) {
$.ajax({
type: "GET",
url: "http://example.com/Private.pl",
data: $('form#chatText').serialize(),
success: function(data) // same data posted by client to server
{
$('#chatText')[0].reset();
$("#chatLog").append(data);
$("#chatLog").scrollTop(999999)
poll();
}
})
event.preventDefault();
}
});
});
function poll() {
$.ajax({
type: 'GET',
url: 'http://example.com/Private.pl',
data: $('form#chatText2').serialize(),
success: function(msg) // other users message from server
{
$('#chatLog').append(msg);
$('#chatLog').scrollTop(999999);
},
complete: poll,
timeout: 500000
});
}
Here is the HTML snippet
<div id='chatLog' class='text-Area'></div>
<textarea name='message'></textarea>
<form id='chatText' method='post'>
<input type='submit' hidden>
</form>
<form id='chatText2' method='post'>
<input type='hidden' name='client' value='0'>
<input type='submit' hidden>
</form>
I found it. In firefox, whenever i type a new text and submit, former polling requests are aborted and a new polling is started. But in chrome, whenever i type a new message a new polling request is added with the old hanging requests. So server is responding every polling requests with same message at same time. The error is calling of poll() method everytime i send a new message..

Categories

Resources