Trouble getting formData to pass to AJAX for file upload - php

I have the following code which passes a file from a form to a PHP script, then depending on what value that script returns, does stuff:
<script>
function upload_img() {
var formData = new FormData($('img_form')[0]);
console.log(formData);
alert("Hello");
var request = $.ajax({
type: 'POST',
url: 'imgupload.php',
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;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
alert("Hello3");
request.done(function(data) {
if (data == 0) {
$('.image_holder').css("background-image", "url(/images/covers/3.jpg)");
alert("image upload succesfull");
}
else {
alert(data);
}
});
}
</script>
<form method="post" id="img_form" enctype="multipart/form-data">
<input type="file" name="img" id="img" style="position:absolute;top:186px;left:420px">
<input type="submit" value="Upload" onClick=upload_img() class="upload_button" />
</form>
However the formData doesn't seem to get passed to the function. I've tried logging formData to the console after it's created but it appears to be empty.

This
$('img_form')[0]
selects all elements looking like
<img_form></img_form>
which you have none ?
This however
$('#img_form')[0]
would select the element with the ID img_form
<form method="post" id="img_form" enctype="multipart/form-data">

Related

Multiple forms with file input on same page

I'm newby with jquery and have a problem with dealing multiple multipart forms on same page. I'm trying to add some data to mysql via php also uploading mp3 files at same time. Each form uses samename+PHPID. There is no problem with first form but im not getting file data when i use other forms. Can anyone help me?
JS:
$(".msc_send_button").click(function(e) { // changed
var a = this.id; // Button id
var form = $('#'+a).parents('form').attr('id'); // Get buttons parent form id
e.preventDefault();
var formData = new FormData($('#'+form)[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
$('#'+a).html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
$('#'+a).html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
PHP Form:
<form name="music-form" id="music-form<?php echo $cont['id']; ?>" enctype="multipart/form-data" novalidate>
<input type="text" name="songno" id="songno" value="<?php echo $cont['song_no']; ?>">
<input type="file" id="mp3" name="mp3" class="inputfile" accept="audio/*" multiple>
<button type="submit" class="msc_send_button" id="msc_send_button<?php echo $cont['id']; ?>">Send</button>
</form>
I think you should change your jquery selector. I didn't see your html codes but you may have created nested forms. Maybe you can use closest('from') instead of parents('form')
$(".msc_send_button").click(function(e) { // changed
var buttonEl = $(this);
var form = buttonEl.closest('form');
e.preventDefault();
var formData = new FormData(form[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
buttonEl.html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
buttonEl.html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});

How to pass file object with multiple attribute via jQuery ajax

I am trying to pass a file object with multiple attribute via AJAX in my WordPress application but not being able to capture them in the process function.
HTML:
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input type="file" multiple" id="photo_upload" name="photo_upload[]" class="files-data" />
<input type="button" value="Submit" onclick="uploadPhoto();" />
</form>
JS:
var formData = new FormData();
formData.append('album_title', jQuery('#album_title').val());
formData.append('security', mbAlbumUploader.ajax_nonce);
jQuery.each(jQuery('.files-data'), function(i, obj) {
jQuery.each(obj.files, function(j, file){
formData.append('files[' + j + ']', file);
});
});
jQuery.ajax({
url: 'mbAlbumUploader.ajax_url,'
type: 'post',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function(response) {
alert(response.files);
}
});
PHP function:
function uploadPhoto() {
$fileName_str = '';
foreach($_FILES['photo_upload']['name'] as $f=>$name) {
$extension = pathinfo($name, PATHINFO_EXTENSION);
$fileName_str .= $name . ', ';
}
die(wp_json_encode(array(
'files' => $fileName_str;
)));
}
What I am doing wrong?
Try to run ajax request by click event or submit event. I made few changes this is script below. Assuming your button has update class.
HTML
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
JavaScript
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'upload.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('album_title', jQuery('#album_title').val());
data.append('security', mbAlbumUploader.ajax_nonce);
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('');
});
PHP (upload.php)
You can Access your files from $_FILES global.

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 make new FormData() work on IE browsers

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();

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