How to pass file object with multiple attribute via jQuery ajax - php

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.

Related

Use single request for both data and file submission to server

A dropzone js need to create a new form but I want to use the same form to post both data and image, how can I achieve this, any idea.
<form method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<!-- how to replace this field with dropzone but in this form in order to use the same ajax as below -->
<input type="file" name="photo" id="photo">
<button type="submit">send</button>
</form>
$("form").on('submit', function(e) {
$.ajax({
url: 'add.php',
type: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function(data) {
if (data.success == false) {
if (data.errors.name) {
$('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
}
if (data.errors.photo) {
$('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
}
}
});
e.preventDefault();
});
You need to append dropzone files separately to FormData. Here is my solution,
$(document).ready(function () {
// get a reference to photo dropzone
var photoDropzone = Dropzone.forElement('#photo-dropzone');
$("form").submit(function (e) {
e.preventDefault();
// create the complete FormData here
var fd = new FormData(this);
// append dropzone files into the form data
for (var i = 0; i < photoDropzone.files.length; i++) {
fd.append('file[]', photoDropzone.files[i]);
}
$.ajax({
url: 'add.php',
type: 'POST',
data: fd,
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function (data) {
console.log('done');
if (data.success == false) {
if (data.errors.name) {
$('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
}
if (data.errors.photo) {
$('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
}
}
});
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/basic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// prevent auto processing in dropzone configuration
Dropzone.options.photoDropzone = {
autoProcessQueue: false
};
</script>
<form method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<button type="submit">send</button>
</form>
<!-- add dropzone form in the same page -->
<form action="add.php" class="dropzone" id="photo-dropzone">

Why page is reloading while uploading file using ajax?

I am using ajax to upload a file from a form. Everything works fine file is uploading, but when I click on the upload button to upload the file after upload the file page gets reloading. How do I prevent the page reloading after file upload?
HTML :
<form enctype="multipart/form-data">
<input type="file" accept=".xlsx" id="file-upload" name="file"/>
<input id="form_submit" value="Upload" type="submit" name="form_submit"/>
</form>
Jquery:
$('#form_submit').on('click', function() {
var file_data = $('#file-upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'file_upload_parser.php', // point to server-side PHP script
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
PHP:
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo "Sucess";
}
Just change the input type 'submit' to 'button'. Because the input type 'submit' does have the default behavior to submit the form. If you change the input type to 'button' and type button does not have the default behavior.
<input id="form_submit" value="Upload" type="submit" name="form_submit"/>
TO
<button id="form_submit" value="Upload" type="button" name="form_submit">Upload</button>
If you want to do this with jquery then just make some changes in jquery function and you can prevent the default behavior of the submit button like below.
$('#form_submit').on('click', function(e) {
e.preventDefault();
var file_data = $('#file-upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'file_upload_parser.php', // point to server-side PHP script
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
and you are free to use
<input id="form_submit" value="Upload" type="submit" name="form_submit"/>
Use jQuery event.preventDefault() Method.
Not like this
$("#form_submit").click(function(event){
// Your upload code here
event.preventDefault();
});
Use like this
$("#form_submit").click(function(event){
event.preventDefault();
// Your upload code here
});
Place event.preventDefault() in the top of the function to prevent the default behavior then write your code.

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

upload more than one image with ajax

I wrote script that alows users to submit comment text with image, and I did it with ajax.
yes - upload image with ajax. it's not drag & drop...
I would like to expand this scrpit and alow users to upload more than one file/image. my code don't support that (server side gets only 1 file). can you help me to fix it so I could upload array of files?
HTML:
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
<input type='hidden' name='comment[pageName]' value='yard' class="pagename-field" />
<input type='hidden' name='comment[refID]' value='0' class="refid-field" />
<input type='hidden' name='allowReply' value='1' class="allowReply-field" />
<textarea class="form-control comment-field" name="comment[text]" rows="1" placeholder="כתוב/י תגובה"></textarea>
<input type='file' name='file[]' class='form-control file-field hideBox' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0"/>
<button class="btn btn-primary submit" >SUBMIT</button>
<img src="images/loading.gif" align="absmiddle" class="loader" id="loader">
</form>
JS:
$(function() {
$(document).on('submit','form',function(e) {
e.preventDefault();
var $form = $(this);
var act = 'add';
var file_data = $form.find('.file-field').prop('files')[0];
var form_data = new FormData();
form_data.append('act', act);
form_data.append('comment[text]', $form.find('.comment-field').val());
form_data.append('comment[pageName]', $form.find('.pagename-field').val());
form_data.append('comment[refID]', $form.find('.refid-field').val());
form_data.append('allowReply', $form.find('.allowReply-field').val());
form_data.append('feel', $form.find('.feel-field').val());
form_data.append('file[]', file_data);
$("#loader").show();
// alert(form_data);
$.ajax({
type: "POST",
url: "ajax/addComment.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
success: function(data)
{
$("#loader").hide();
$('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
$("form").reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
You can do it by FormData() object of jQuery. Refer the code below.
HTML:
<input type="file" name="multi_upload[]" multiple />
JQuery:
$(function() {
$(document).on('submit','form',function(e) {
var files = e.target.files;
var data = new FormData();
$.each(files, function (key, value)
{
data.append(key, value);
});
$.ajax({
url: "your-url",
type: 'POST',
data: data,
cache: false,
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("success");
}
});
});
});
PHP:
$tempfiles = $_FILES;
foreach ($tempfiles as $files) {
$_FILES['multi_upload'] = $files;
move_uploaded_file($_FILES['multi_upload']['tmp_name'],$_FILES['multi_upload']['name']);
}

How to get the uploaded image using PHP via AJAX

I need to get the uploaded image using PHP via Ajax
My form fields are,
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="button" id="bidm" name="bidm" value="Next"/>
</form>
In ajax call I have following code :-
$.ajax({
url: './api/addspot.php',
data: $('#rent_details').serialize(),
type: 'POST',
contentType: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
Here I got only spottype value in Ajax success function .But I need to get
all form fields value.
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="submit" id="bidm" name="bidm" value="Next"/>
</form>
$(document).ready(function(){
$("#rent_details").submit(function(e){
e.preventDefault();
$.ajax({
method:'POST',
url: "./api/addspot.php",
data: new FormData( this ),
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
});
});
And get by name on your requested page. use $_FILES for upload files.
This will work.
$('#rent_details').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: './api/addspot.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}));
Need to use the FormData() for the ajax data. It took all the form variables and passed it to the ajax. Then in the ajax function, you can retrieve the file name and the temp file name and save the image file to the folder where you required to save.
You need to use the FormData();
Know that this code will not work on IE9 and lower.
This is for multiple file upload.
$(document).on('click', '#bidm', function(e) {
e.preventDefault();
var request = new FormData(this);
var my_files = $(this).closest('form').find('#fileToUpload').files;
$.each(my_files, function(j,file) {
` request.append('fileToUpload['+j+']', file);
});
$.ajax({
url: './api/addspot.php',
data: request,
dataType: "json",
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
Try this to get file field value:
$('input[type=file]').val()
This code is worked

Categories