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();
}
}
});
Related
I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>
Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!
Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']
Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input
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?
I have a simple multipart/form-data form submitted with ajax after validation using jQuery Validation Plugin.
I disable the submit button before submit and after successful form submission enable the submit button and reset all the form fields. The form code is working on Chromium Browser on a Debian Box.
Is there a better/cleaner way of doing this?
<form class="aForm" enctype="multipart/form-data">
File To Upload: <input class="aData" type="file" name="aData" /><br/>
Name of User: <input type="text" name="aName" class="aName" placeholder="Name"
/><br/>
Date: <input type="text" name="aDate" class="aDate" placeholder="Date" /></br/>
<input type="hidden" value="5f25c045bf33ac72fcf5f8bc23b4c862d220d385" name="csrfToken" >
<button class="aButton">Button</button>
</form>
$(document).ready(function(){
$(".aForm").validate({
rules: {
aData: {
required: true,
extension: "png|jpg",
},
aName: "required",
aDate: "required"
},
messages: {
aData: "No Data",
aName: "No Name",
aDate: "No Date"
},
submitHandler: function(){
$('.aButton').prop('disabled', true);
var formData = new FormData($('.aForm')[0]);
console.log(formData);
$.ajax({
url: 'ajax.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success:
function(data){
alert(data);
$('.aForm')[0].reset();
$('.aButton').prop('disabled', false);
},
error:
function(jqXHR, textStatus){
console.log(textStatus);
}
});
}
});
});
Above block of codes are working in live production without any problem. Tested on IE9 to IE 11, Chrome on windows and Linux. There are no Firefox users.
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>