Post FormData not working in IE9 - javascript

The following code does not post the file data to the server in IE9.
FormData() object looks to be the issue but not sure how to resolve it.
I used form.serialize() but this is not uploading the file.
Im hesitant to implement a JQuery file uploader just for this function.
Is there a simple way to upload a file similar to FormData() ?
// HTML
<form name='aform' action='upload.php'>
<input type='file' name='afile'>
<input type='text' name='qty' value='1'>
<input type='hidden' name='product_id' value='7'>
<a class='addToCartButton'>Add to cart</a>
</form>
// JS
$(document).on('click', '.addToCartButton', function(event)
{
var form_id = $(this).closest('form').attr('id');
var formElement = document.getElementById(form_id);
var odata = new FormData(formElement);
//var $form = $('#'+form_id);
$.ajax({
url: 'http://localhost/cart/add',
data: odata, //$form.serialize(),
type: 'POST',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data)
{
var returnObject = jQuery.parseJSON(data);
switch(returnObject.status) {
case 'success':
alert('Item added to cart');
break;
case 'error':
alert('An error occured');
break;
case 'no_file':
alert('No file was detected');
break;
}
});
event.preventDefault();
});

It's because IE9 does not support it.
http://caniuse.com/#search=formdata
Fully related : Post formdata via XMLHttpRequest object in JS ? ( cross browser)

Related

subscriber is not working properly using ajax

In my footer i have a subscriber form in which any user can subscribe to website.
Form is
<form id="newsletter-signup" action="?action=signup" method="post">
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="submit" id="signup-button" value="" />
</form>
I want to use ajax for submitting data in the database. i have never used ajax before so there is a problem in it and i cant solve it.I have used action action="?action=signup" due to which whenever i clicked on this it goes to 404.html. All the other tasks are working fine . Email is stored in database and all other checks are also working fine. I want this that it does not go to 404.html page . instead of this it should display this message that subscribed successfully.Script portion is this.
Script
$(document).ready(function() {
$('#newsletter-signup').submit(function() {
//check the form is not currently submitting
if ($(this).data('formstatus') !== 'submitting') {
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus', 'submitting');
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success: function(data) {
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch (responseData.status) {
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
});
}
});
}
//prevent form from submitting
return false;
});
Data is stored in database as this
if($_GET['action'] == 'signup'){
//Data storing code
}
all these files are in footer.php.
Seems you have some syntax error after success function.
I updated the code like this after document ready
$('#newsletter-signup').submit(function(e) {
e.preventDefault();
//check the form is not currently submitting
if ($(this).data('formstatus') !== 'submitting') {
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus', 'submitting');
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success: function(data) {alert(data);
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch (responseData.status) {
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
}
})
}
});
Try to use some debugging tools like firebug. Please try to update the code and check.
Try this it will work :
Correction in your Html Form Code :
<form id="newsletter-signup" action="#123" method="post">
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="submit" id="signup-button" value="" />
</form>
Don't use ?action=signup give proper page path i.e.page.php?action=signup or use ajax call to save the form data and show the successful message on same page.
Correction in your Script code :
$(document).ready(function() {
$('#newsletter-signup').submit(function() {
console.log("rohit");
return false;
//check the form is not currently submitting
if ($(this).data('formstatus') !== 'submitting') {
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = 'page.php?action=signup',
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus', 'submitting');
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success: function(data) {
//setup variables
var responseData = jQuery.parseJSON(data),
class = '';
//response conditional
switch (responseData.status) {
case 'error':
class = 'response-error';
break;
case 'success':
class = 'response-success';
break;
}
}
});
}
});
//prevent form from submitting
return false;
});
page.php :
if($_GET['action'] == 'signup'){
// Your code comes here.
}

send file using ajax with other type of input

i already had a form which uses ajax to save the the data to the database. so i have this sample
Html code
<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>
Javascrip Code
$("#btnSave").click(function(){
p_name = $("#product_name").val();
p_des = $("#product_description").val();
p_image = $("#product_img").prop('files')[0];
data = {
'product_name':p_name,
'product_description':p_des
}
$.post('url_here',data,function(response){
console.log(response);
});
});
i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.
You can use FormData:
document.getElementById('btnSave').addEventListener('click', function() {
var fd = new FormData();
fd.append('product_name', document.getElementById('product_name').value);
fd.append('product_description', document.getElementById('product_description').value);
fd.append('product_name', document.getElementById('product_img').files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url_here');
xhr.addEventListener('load', function(e) {
console.log(xhr.responseText);
});
xhr.send(fd);
});
UPDATE
Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:
$('#btnSave').click(function() {
p_name = $('#product_name').val();
p_des = $('#product_description').val();
p_image = $('#product_img').prop('files')[0];
var data = new FormData();
data.append('product_name', p_name);
data.append('product_description', p_des);
data.appned('product_img', p_image);
$.ajax({
url: 'url_here',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
});

Post a form without uploading files for validation

I have a form with files. I would like to perform a server-side validation and only then upload the files (since each file makes the request larger).
Is there slick way to do that doesn't include serializing the form's data and running an ajax?
I'm not looking for something like this:
var formData = $('#form').serializeArray();
$.post(url, formData, function(res){
if(res.isValid)
$('#form').submit();
});
Try something like this (for Client side validation) , onclick of submit button
var file = $('#file_upload').prop("files")[0]; //file_upload is form's id
var name = file.name;
var size = file.size;
var type = file.type;
if (type != 'image/png' && type != 'image/jpeg' )throw {"msg": 'Invalid image type'}
if (size > 1024 * 1024 * 2 )throw {"msg": 'Invalid image size'}
And for AJAX Server Side Validation before upload, you need to send file object via Ajax( ***not recommended, might not work in few old browsers)
try {
var formObj = new FormData($('form')[1]); //File Object
$.ajax({
url: "YOUR URL", // do the SERVER SIDE VALIDATION here
data: formObj,
processData: false,
contentType: false,
dataType:'json',
type: 'POST',
success: function(data){
// Success code
}
});
}catch (e) {
console.log(e.msg);
}
out.html is entry point. submitValidate submits form in iframe (in.html). JavaScript snippet (confirm.html) in response from server passes database record to validateClientSideAndUpload which sets hidden field and submits form in parent window to server. Server moves file to appropriate location and creates association with record speficied by id. Posted as a proof of concept.
out.html
<script>
function submitValidate() {
document.getElementById('validate-frame')
.contentDocument.querySelector('form').submit();
}
function validateClientSideAndUpload(id) {
if(document.getElementById('file').value === '') {
alert('Select file');
return;
}
document.getElementById('record-id').value = id;
var form = document.querySelector('form');
if confirm('Upload file?') {
form.submit();
}
}
</script>
<iframe src="in.html" id="validate-frame"></iframe>
<form>
<input type="file" id="file"/>
<input type="hidden" id="record-id"/>
</form>
<button onclick="submitValidate()">Save</button>
in.html (new/invalid)
<form action="confirm.html">
<label>Name</label>
<input type="text" placeholder="data">
</form>
confirm.html (success)
<script>
window.onload = function() {
parent.validateClientSideAndUpload(/* server generated record id */);
}
</script>

how to upload file using ajax request with sinatra?

i'm tring to upload file using jquery ajax function with ruby-sinatra function. here is my code.
<form id="ucform" method="post" action="#" enctype="multipart/form-data">
<input type="file" id="cfile" name="cfile" onchange="prepareUpload(this.files)">
<button type="submit">Update</button>
</form>\
javascript code
var ufiles;
function prepareUpload(files)
{
ufiles = files
}
$(function(){
$('#ucform').on('submit', uploadFiles);
});
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
//alert(ufiles);
// Create a formdata object and add the files
var data = new FormData();
$.each(ufiles, function(key, value)
{
data.append(key, value);
});
alert(data);
$.ajax({
url: '/upload_cfiles',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
alert(data);
}
});
}
sinatra function
post '/upload_cfiles' do
begin
File.open('applications/QOS/conf/' + params['cfile'][:filename], "w") do |f|
f.write(params['cfile'][:tempfile].read)
end
return "The file was successfully uploaded!"
rescue Exception => e
return e.message
end
end
above code return bellow error
ERRORS: parsererror
undefined method `[]' for nil:NilClass
please help me to solve this error
It's a safe bet that params['cfile'] is nil. Have you actually logged your request parameters to ensure you are posting what you think you're posting?
Furthermore, I believe that you're trying to upload these files using JSON - you will most likely need to base64 encode the body of the file to do this.

Is the FormData object available in Internet Explorer 10?

I'm writing a little JavaScript application that allows me to upload images asynchronously.
This script works awesome in every browser except for, guess who, Internet Explorer...
So the first thing that I made is to create a fallback for IE9- versions with AjaxForm Plugin for jQuery, which works great!
Here's the JS script.
$("#Uploader").change(function(e){
var form = $("#UploaderForm");
form.trigger('submit');
$(this).attr('disabled','disabled');
e.preventDefault();
});
$("#UploaderForm").submit(function(e){
e.preventDefault();
e.stopPropagation();
var type="POST";var loading=$("#PhotoIsLoading");
if(windowApi === true){
var formData = new FormData($(this)[0]);
$.ajax({
url: url,
type: type,
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ myXhr.upload.addEventListener('progress',progressHandlingFunction, false);}
return myXhr;
},
beforeSend: function(){loading.removeClass('isHidden_important');},
success: function(response){
jres = JSON.parse(response);
alert("Test ok, file uploaded");
},
error: function(response){console.warn(response);},
data: formData,
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
}else{
$(this).ajaxSubmit({
url: url,
dataType: 'json',
type: type,
beforeSubmit: function(){loading.removeClass('isHidden_important');$(this).formSerialize();},
success:function(response){
jres = JSON.parse(response);
alert("FallbackTest Complete");
},
error: function(response){console.warn(response);},
});
e.preventDefault();
return false;
}
});
WindowApi and every other variable are defined in a global script but don't worry, they work. To be precise, WindowApi is this:
var windowApi=true;
if(window.File&&window.FileReader&&window.FileList&&window.Blob){
console.log("window.api ready");windowApi=true;}
else{console.log("window.api not ready");windowApi=false;};
So, with this bunch of lines of code I handle every browser and IE9- browsers...
The problem now is with IE10 because it has got all the window.* methods and it can use the FormData object. But when I try to upload something with IE10 and FormData I receive an "Access Is Denied" error for the formData object.
The HTML that is involve in this process is:
<form name="UploaderForm" id="UploaderForm" method="post" enctype="multipart/form-data">
<input type="file" name="Uploader" id="Uploader" accept="image/*" tabindex="1" />
</form>
So at the end my question is:
How can I avoid getting an "Access Denied" exception in IE10 when trying to access the FormData Object?
https://stackoverflow.com/a/13657047/641293 and https://stackoverflow.com/a/4335390/641293 might be useful. IE is quite strict about what you can do with <input type='file'> programmatically.
Based on the first one, does changing the first line to this fix things?
$("#Uploader").on('click', function(e){ /* rest of the function unchanged... */
You get an access denied when you submit a form that has fields that have been messed with by javascript. You added dynamically the disabled attribute on your uploadfield, that could be the reason that you receive an Access denied. Maybe you should give it a shot without the disabling of the field on the change event?
By the way, you might be better off checking the availability of FormData in combination with the File API:
var formDataSupport = false;
if (typeof FormData === 'function' &&
window.File &&
window.FileReader &&
window.FileList &&
window.Blob)
{
console.log("File API available, formData available");
formDataSupport = true;
}

Categories