how to make new FormData() work on IE browsers - php

How can I make this work on IE?
This won't work on IE, new FormData() api is not supported by IE browsers, is there any other api equivalent to new FormData() in IE?
var fd = new FormData();
fd.append( "userfile", $("#userfile")[0].files[0]);
$.ajax({
url : '/user/ajax_upload/',
type: 'POST',
contentType:false,
cache: false,
data: fd,
processData: false,
beforeSend :function(){
},
success : function( data ) {
$('#popupbox').html(data);
}
});

Its better to use jquery form Js for submitting images over ajax. I found it better than FormData()
<script type="text/javascript" src="/js/jquery.form.js"></script>
function update_professional_details(){
var options = {
url : '/validateform/personal',
type : $("#personal_edit_form").attr('method'),
dataType: 'json',
success:function( data ) {
var msg = data.msg;
if(data.status == 'success'){
$("#msg_data").html("Updated successfully, redirecting...")
$("#personal_edit_form").submit();
}else{
$('p[class$="_error2"]').html('');
var msg = data.msg;
$.each(msg, function(k, v) {
$('.'+k+'_error2').html(v);
});
}
},
};
$('#personal_edit_form').ajaxSubmit(options);
return false;
}
$('#updatepersonal').click(function(){
update_professional_details();
return false;
});

Actually i made an alteration to my code to be able to use $.ajax in all other browsers and just made an iframe for the IE browsers like this.
mailer.php
<!--[if IE]>
<iframe src="form.php"></iframe>
<![endif]-->
<![if !IE]>
<script>
$(document).ready( function() {
//Program a custom submit function for the form
$("#form").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: $("#form").attr('action'),
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
});
</script>
<?php include_once ('form.php'); ?>
<div id="email-success"></div>
<![endif]>
form.php
<form id="form" action="form-exec.php" target="_self" method="post" enctype="multipart/form-data">
<input type="text" name="email-to" value="" />
<input type="text" name="email-subject" value="" />
<input type="text" name="email-message" value="" />
<input type="file" name="file" />
<input type="file" name="file2" />
<button type="submit" name="email-send">Skicka</button>
</form>
and the form-exec.php is, in my case, my PHPmailer sender!

AFAIK it is possible in IE9+ only.
To upload file 'ajax like' you should use iframe trick for that.
I used that as source when implementing it:
http://ramui.com/articles/ajax-file-upload-using-iframe.html

Apparently, FormData is not supported in IE. You may, however, be able to use jQuery's serialize like so:
var FD = $('form').serialize();

Related

Jquery change not working with Ajax call inside [duplicate]

For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});

Why aren't the Attachments in my Contact Form coming through? [duplicate]

This is my HTML which I'm generating dynamically using drag and drop functionality.
<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>
<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
This is my JavaScript code:
<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);
$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.

Appending form inputs to Formdata Object not working

I have a form which is for sending mails.It contain fields such as to_name,subject,message and attachment button.I will create a file input field on clicking the button with class .file_add_btn.
//click event for add files
$(".file_add_btn").click(function(){
if($("#file_div").html() == '')
{
$("#file_div").append('<div class="file_btn_div" id="file_btn_div_first"><input type="file" class="btn_browse" name="file_uploads[]">'+
'<input type="button" class="del_file" value="X"></div>');
}
else
{
if($(document).find('.btn_browse:last').get(0).files.length !==0)
{
$("#file_div").append('<div class="file_btn_div"><input type="file" class="btn_browse" name="file_uploads[]">'+
'<input type="button" class="del_file" value="X"></div>');
}
}
});
I write the following function to include file inputs into formData.
$.fn.serializefiles = function() {
var obj = $(this);
var form_data = new FormData(this[0]);
$.each($(obj).find('.btn_browse'), function(i, tag) {
$.each(tag.files, function(i, file) {
console.log(tag.name+' '+file.name)//this is printing in console
form_data.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
console.log(val.name+'<br/>');
console.log(val.value+'<br/>');
**//here file names are not coming.All other elements are coming.They are not adding to form_data object**
form_data.append(val.name, val.value);
});
return form_data;
};
My ajax call is like the following:
$.ajax({
type: "POST",
url: 'process.php',
data: $("#compose_message").serializefiles() ,//formID=#compose_message
asyn: true,
cache: false,
processData: false,
contentType: false,
success:function()
....
I am not able to append the inputs into the form_data object.In console,I see [object FormData] inside the POST on button click.
Edit: My initial comment above was correct. You don't need to do anything fancy except pass the form object into FormData constructor as shown in my example below.
console.log(JSON.stringify(formData)); will never show the values of the FormData. However, if you look in your browser's network tab, the request that gets sent will show the values being passed.
If you want to check the data before it is being passed, you could use this answer.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
input {
float: left;
clear: left;
}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="text" name="text" value="text">
<input type="hidden" name="hidden" value="hidden">
<input type="file" name="file_uploads[]" value="">
<input type="file" name="file_uploads[]" value="">
<input type="file" name="file_uploads[]" value="">
<input type="button" value="Add">
<input type="submit" value="Submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
console.log(JSON.stringify(formData)); // will always be {}
$.ajax({ url: '404', type: 'post', data: formData, processData: false, contentType: false });
});
$('[type=button]').on('click', function () {
$(this).before('<input type="file" name="file_uploads[]" value="">');
});
});
</script>
</body>
</html>
specify exact data for formdata
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Main magic with files here
formData.append('image', $('input[type=file]')[0].files[0]);
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
try this
var form = $("form")[0]; // You need to use standard javascript object here
var formData = new FormData(form);
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Main magic with files here
formData.append('image', $('input[type=file]')[0].files[0]);

Can't get inputType='file' data on form submit

In jQuery, when a function got success a form getting build. Now when I submit this form it gives all data except inputType='file'. I can't get it why this is happening
here is my jQuery code when form is creating
content += '<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data">'+
'<input type="text" name="album_id" value="'+id+'">'+
'<input type="text" name="user_id" value="'+user_id+'">'+
'<input type="file" name="image" id="image_upload">'+
'<input type="submit" value="Submit">'+
'</form>';
Here form is getting submit
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
console.log(data);
});
return false;
});
I am sending this form data in a controller in cakephp.
In controller I get only input field data with text type only. But I need file type too.
please use jquery.form.js for file upload.
http://malsup.com/jquery/form/
<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data" onsubmit="return submit_form();" >
function submit_form(){
$('#data').ajaxSubmit({
method:'post',
dataType:'json',
success: function(resp){
}
});
return false;
}
You can change jquery function like this
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});

how to Upload file asynchronously using JQuery

I want to upload a file asynchronously using jQuery - without using any PLUGIN.
JQuery is very new to me and after looking at various forums I ended up with this code :
HTML:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#myform').submit(function() {
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
type: "POST",
url: "upload.php",
data: formData,
processData: false,
contentType: 'multipart/form-data',
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
success:function(msg){
//alert( "Data Uploaded: " + msg );
document.getElementById('display').innerHTML = msg;
}
});
return false;
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" id="myform" name="myform" method="POST">
<input name="file" type="file" id="file" name="file"/>
<input type="text" name="txtValue" value="" id="txtValue">-->
<input type="submit" value="Upload" id="button" name="button"/>
<div id="display"></div>
</form>
</body>
</html>
PHP:
<?php
$uploaddir = './uploads/';
$file = $uploaddir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
$value = "success";
}
else {
$value = "error";
}
echo $value;
?>
This code is not working and everytime the "display" DIV is printing "error". Please help me out.
Take a hidden div. Inside that div take a iframe and set the form's target to the iframe's id.
In jQuery. In after document ready function add a load event handler (say LEH)to the iframe.
So that when the form is submitted and file is uploaded and iframe is loaded then the LEH will get called
This will act like success event.
Note: you need to make minor tweaks as for the first time when the page is loaded then also the iframe is loaded. So there will be a first time check also.
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div).
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
You can do some validation if you want.
$(':file').change(function(){
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
//Your validation
});
Now the Ajax submit with the button's click:
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Now if you want to handle the progress.
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
SOURCE
You can use following plugins to upload files using ajax:
jQuery Form Plugin
Uploadify
The plugin in the first link provides some very useful callbacks. You can check the documentation at the given link.
I have user Jquery Form Plugin in my project.
JQuery the raw xhr object is wrapped in jqXhr Object which doesn't have any reference to the new upload property of the xhr.
Hope you can start with this below example.
html:
<input type="file" class="text-input" size="50" id="file_upload" value="" name="file_upload"/>
var formData = new FormData($('form')[0]);
$.ajax({
url: '/files/add_file', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
//myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
dataType: 'JSON',
beforeSend: beforeSendHandler,
success: function(data) {
if (data.error){
showMessage(data.html, false, false);
}
else{
showMessage(data.html, false, false);
setTimeout("window.location = 'path/to/after/uploading';",450)
}
},
error: function(data) {
showMessage(data.html, false, false);
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});

Categories