FormData ajax upload on IE8 -> alternatives and how it works - javascript

I'm tyring to upload a picture with ajax, so I'm using FormData, but it's not working with IE8. I've looked about it and it's not possible to use FormData with IE8, but I've found nothing I've been able to use instead in order to make it work on IE8 and other browser. Could someone tell me what to do please, and how to do it ?
The form I'm trying to submit
<form id="addImgForm" name="addImgForm" method="post" action="#URL(Action('ChiliTest-ImageUpload'))#" enctype="multipart/form-data">
<input id="newImage" type="file" name="newImage">
<input type="hidden" name="MAX_FILE_SIZE" value="12345">
<span id="addImage" class="button-addImage" type="submit"><isTradConstant keyword="l_customizationsChiliEditor_AddImageButtonTitle" template="CustomizationsChiliEditor" init="Ajouter"></span>
</form>
Called on addImgForm submit
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
return false;

Ideally when i faced this issue, i checked for FormData in browser and if that returns undefined, then i went for form submission via an iframe.

We have used jquery plugin for the same and got resolved this issue.
It is too simple just use
$('#myForm').ajaxForm(function() {
});
instead of below call, it set all options automatically.
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
Hope this will work out, let me know if any hurdles during implementation. Make sure you added jquery plugin before using ajaxform function. Do not need to do anything for other browser it works for IE and other both.

You can use [jQuery Form Plugin][1] to upload files via ajax in IE 8 and your example code should be like this:
[1]:
$(document).ready(function() {
var options = {
beforeSend: function() {
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
$("#bar").width(percentComplete + '%');
$("#percent").html(percentComplete + '%');
},
success: function() {
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response) {
$("#message").html("<font color='green'>" + response.responseText + "</font>");
},
error: function() {
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
<script src="http://malsup.github.io/min/jquery.form.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<form id="myForm" action="/demo/Upload" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div>
</div>
<br/>
<div id="message"></div>

Related

Image Upload at Google Appengine using AJAX and PHP

I'm trying to upload an image on Google appengine hosting using ajax and php and I always get server error 500
My approach is create upload url which will be later used to submit the form to:
<?php
$upload_url = CloudStorageTools::createUploadUrl('/upload_script', $options);
The form which will be submitted as soon as any change is made to the input type file:
<form <?php echo 'action="$upload_url"'; ?> enctype="multipart/form-data" method="post">
Files to upload: <br>
<input type="file" name="uploaded_files" size="40">
<input type="submit" value="Send">
</form>
Since I'm doing it using AJAX here is the ajax code:
$(document).ready(function () {
$('#form').on('submit',(function(event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(){
console.log("success");
},
error: function(){
console.log("error");
}
});
}));
$("#browse").on("change", function() {
$("#form").submit();
});
});
This produces server error 500 when looking on it in console does anyone know where might be the problem?

What about Dropzone.js within an existing form submitted by AJAX?

Ok, here is the scenario. I have already a form having some input fields, some radio buttons and an input type=file. There is a button for submitting the whole form using AJAX.
Everything was working fine, until i decided to change the input type=file with the more fancy DropZone.js
Now i have the following html code (a sample here):
<form enctype="multipart/form-data" id="test_form" name="test_form" class="form uniformForm">
<input class="form-control" type="text" value="" name="a-name" id="a-name" />
<label for="a-name">Field Name</label>
<div class="dropzone dropzone-previews" id="my-awesome-dropzone </div>
</form>
<button class="btn btn-primary btn-large" id="submitForm"> Submit </button>
I have the following js (jQuery), too:
$("button#submitForm").click(function(){
var fd = new FormData(document.getElementById("test_form"));
fd.append("label", "WEBUPLOAD");
$.ajax({
type: "POST",
url: "create_form.php",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
});
});
$("div#my-awesome-dropzone").dropzone({
url: "#",
paramName: "creative_file",
maxFilesize: 1,
autoProcessQueue: false
});
In documentation of Dropzone.js says that the dropzone div looks like <input type="file" name="file" />. The only difference is that i want to rename the input name as creative_file.
I have 2 question.
1) This doesn't work. When pressing the Submit button, i have FIREBUG opened and i check what it sends as POST. It sends everything except the files. No creative_file, no file at all.
2) If finally figured out how to make it works, is there any way to have a fallback with this implementation especially for the iOS or Android devices ?
1)
$("#salvar").on('click',function(e) {
if ($("#psl_titulo").val() == "") {
alert('Empty');
} else {
e.preventDefault();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
$("#my-awesome-dropzone").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.href = url_redirect;
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Ocorreu um erro ao salvar ao enviar os dados. Erro: ' + textStatus);
}
});
e.preventDefault();
});
$("#my-awesome-dropzone").submit();
}
}
});

Facing AJAX issue with JSP

I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});

Submit unresponsive after ajax call + fadeIn()

Good day, fellow programmers.
There's this index.php that does an Ajax call to login.php and appends the DOM elements and some javascript from inside this into the body of the index. This login.php consists out of a a single div that contains a form and a submit button, which fadeIn() as soon as it is all appended.
However: the submit button is unresponsive!
I did find, after a while, that this does not happen when you directly access login.php via URL (.../.../login.php) instead. This means it's the fact that the index appends the whole, which makes them unresponsive.
(Also: in light of this, I've added a $(document).ready(function(){ ... }); around the entire script in the login.php, but that did not seem to help at all. Instead it caused all functions to return errors...)
I'm out of ideas. Perhaps some of you might have had any experience with these matters?
As always, thank you for the time!
Here's the (simplified) code:
index.php
$('#logInButton').click(function(){
loadContent('/login/login.php', 'body');
});
loadContent();
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
}
});
}
}
login.php (deleted some styling. If you want some specific info, just ask!)
<style>
// some styling
</style>
<div id="loginBlack">
<div class="login" style="z-index:9999;">
<form id="myform1" name="myform1">
<div>
<img src="images/inputEmail.png" />
<div id="emailOverlay">
<input id="email" type="text"/>
</div>
</div>
<input id="iets" name="iets" type="submit"/>
</form>
</div>
</div>
<script type="text/javascript">
// $(document).ready(function(){ // <-- been trying this out.
$('#loginBlack').fadeIn(t)
// some functions pertaining to logging in and registering
// });
</script>
Use jquery on() instead of click()
$('body').on('click', '#logInButton' ,function(){
loadContent('/login/login.php', 'body');
});
That should make the elements behave properly
Note: you can also replace body selector with something nearer to the click button ( its nearest parent )
EDIT::
With this you can have the styling in your normal css file. Put it outside of the login.php
And your js goes into into the success handlers. So just leave the php with the actual html
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
}
});
}
}

Jquery Ajax request Fail

I have a web service that does work properly when asked directly by url but i cant seem to call it through a Jquery Ajax call.
Here's my code:
jQuery("#field1").focusout(function() {
alert("focusOut");
jQuery.ajax({
type: 'POST',
url: '/motifRes/name',
data: { 'clRef' : document.getElementById("field1") },
datatype: 'text',
success: function(msg) {
$("#nomClient").val(msg);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
});
I do enter in the function because i get the "focusOut" alert but then nothing, just nothing.
I used the Chrome developper tool and fiddler and I see no request, no error.
Any ideas ?
EDIT:
About your questions :
are you requesting from an external domain?
Blockquote
No I am not
Are you sure its a POST request?
Well either way, it doesnt change a thing =/
Here's my HTML
<div class="panel" id="standard">
<form id="test" action="#" method="get">
<fieldset>
<legend>Formulaire de changement du motif d'annulation</legend>
<div class="form-row">
<div class="field-label"><label for="field1">Ref Client</label>:</div>
<div class="field-widget"><input name="field1" id="field1" title="Entrer la référence client" /><input id="nomClient" readonly="readonly" type="text" value=""></input></div>
</div>
Use done(), fail(), and always() instead of success() and error(). Also use document.getElementById("field1").value instead of document.getElementById("field1").
jQuery("#field1").focusout(function() {
alert("focusOut");
jQuery.ajax({
type: 'POST',
url: '/motifRes/name',
data: { 'clRef' : document.getElementById("field1").value },
datatype: 'text',
done: function(msg) {
$("#nomClient").val(msg);
},
fail: function (xmlHttpRequest, textStatus) {
alert(textStatus);
}
});
});
Change your data attribute to
data: { 'clRef' : $("#field1").val() },
Finally got it. A vicious and well rookie mistake I guess...
url: '/motifRes/name'
=!
url: 'motifRes/name'
The slash does mean an absolute path and without it the root of my webservice does concat with the url...

Categories

Resources