Multiple file upload using ajax in wordpress - javascript

I am trying to upload multiple images from one input field and want to send form-data with images and action via ajax. Below I am sharing my code
jQuery(document).ready(function() {
var ajax_url = 'admin-ajax.php';
// When the Upload button is clicked...
jQuery(document).on('click', '#upload_multiImages', function(e){
e.preventDefault;
var fd = new FormData();
var files_data = jQuery('.files-data'); // The <input type="file" /> field
// Loop through each data and create an array file[] containing our files data.
jQuery.each($(files_data), function(i, obj) {
jQuery.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
// our AJAX identifier
fd.append('action', 'cvf_upload_files');
jQuery.ajax({
type: 'POST',
url: ajax_url,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
jQuery('.upload-response').html(response); // Append Server Response
}
});
});
});
<input name="my_file_upload[]" id="my_file_upload" type="file" multiple="multiple" accept = "image/*" class="files-data form-control multi with-preview" value="Drag and Drop" />
<input name="all_vendor_file" type="hidden" value="<?php //echo implode(',', $vendor_images);?>">
<button type="submit" name="upload" id="upload_multiImages">Upload</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
But in response I am only getting action files are not appending, due to which I am not able to get files data over ajax function.

Related

How to work with filepond plugin, ajax and php, file name not detected on the server

I am trying to upload file to an xammp server. I'm unable to access the file it uploaded. I doubt on this link server: 'http://localhost/', because when I change it to the name of PHP file that process data on the server side it works.
But also I added another field called username on the form, look below on the code, and I want to combine them on single submit event with Ajax, but I have no idea for this combination.
//initialize file pond with jquery plugin
$('#file').filepond({
allowMultiple: false,
server: 'http://localhost/'
});
//ajax
$("form").on('submit', function(e) {
$.ajax({
url: 'send.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.username) {
$('#username').append('<span class="text-danger">' + data.errors.username + '</span>');
}
if (data.errors.file) {
$('#file').append('<span class="text-danger">' + data.errors.file + '</span>');
}
}
});
e.preventDefault();
});
//my form field between form tag
<form method="POST" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="file" id="file">
</form>
//php code validate file and name
$errors = [];
if(empty($_FILES['username'])) {
$errors['username'] = 'Enter your name!';
}
//other validation goes here...
if(empty($_FILES['file']['name'])) {
$errors['file'] = 'upload file!';
}
//other validation goes here...
echo json_encode($errors);
EDIT:
I notice that the name attribute in the input type file is not available/removed by the plugin and the input ID is also overwritten every time i load the page,
//example the input look like where the id="filepond--browser-men6qus3m" change every time i load new file
<input class="filepond--browser" type="file" id="filepond--browser-men6qus3m" aria-controls="filepond--assistant-men6qus3m" aria-labelledby="filepond--drop-label-men6qus3m" accept="image/png">
Thus why i get undefine typoerror and the file not attached
You are going to send a FormData with Ajax request. The problem you've mentioned here is that you want to include the file which is attached using FilePond library. Here is my solution to append FilePond files to a FormData:
$(document).ready(function () {
pond = FilePond.create(
document.querySelector('#file'), {
allowMultiple: true,
instantUpload: false,
allowProcess: false
});
$("#upload_form").submit(function (e) {
e.preventDefault();
var fd = new FormData(this);
// append files array into the form data
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
fd.append('file[]', pondFiles[i].file);
}
$.ajax({
url: 'fileupload2.php',
type: 'POST',
data: fd,
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (data) {
// todo the logic
// remove the files from filepond, etc
},
error: function (data) {
// todo the logic
}
}
);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
<form id="upload_form" method="POST" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="file" id="file" class="filepond">
<input type="submit" value="Upload"/>
</form>
And on your PHP side, you need can get the files like this:
$errors = [];
if (empty($_POST["username"])) {
$errors['username'] = 'Enter your name!';
}
// check if file is set and uploaded.
if (!isset($_FILES['file']) || $_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
$errors['file'] = 'upload file!';
} else {
$filesNum = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $filesNum; $i++) {
// same the file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i]);
}
}
// Other validation goes here...
// Return the proper response to the client
// I'll leave this to you
And note that:
I've disabled instantUpload and allowProcess on FilePond to prevent auto uploading and processing.
Your PHP side needs more validation and also it should return proper response to the Ajax.

Uploading xml file and image file together with same submit using one ajax call

I want to send uploaded image and uploaded XML to PHP file using one ajax. I used two form data, Is this the correct way to do it.
<input type="file" class="form-control-file" name="fileToUpload" id="uploadFile"/>
<input type="file" name="imageToUpload" id="uploadImg"/>
<input type="submit" id="upload_xml" name="transcriptform" value="Upload File" class="btn btn-info">
Ajax call:
$('#upload_xml').on('click', function() {
var file_data = $('#uploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var img_data = $('#uploadImg').prop(files('files')[0];
var img_form = new FormData();
img_form.append('img', img_data);
$.ajax({
url: "get_old_contents.php",
//dataType: 'script',
//cache: false,
contentType: false,
processData: false,
data: form_data,img_form; //is this correct
type: 'post',
complete: function(response){
$('#res').html('Your files are uploaded successfully!');
}
});
});
Not quite. You need to send a single FormData object in the data property of the $.ajax call. To do that you can use append() to add both files together, like this:
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#uploadFile').prop('files')[0];
var img_data = $('#uploadImg').prop('files')[0];
form_data.append('file', file_data);
form_data.append('img', img_data);
$.ajax({
// ...
data: form_data,
});
});
You can also simplify this if you can change the name attribute of the file inputs, by providing a reference to the <form> element to the constructor of the FormData object:
<input type="file" class="form-control-file" name="file" id="uploadFile"/>
<input type="file" name="img" id="uploadImg"/>
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
// ...
data: form_data,
});
});
Note that in both cases you should be hooking to the submit event of the form element, not click of the button, and using preventDefault() on the event argument of the handler to stop the standard form submission.

send image url and data through serialization

I am trying to make a form where there will be user data(name,dob etc) and an image. When user submits the form a pdf will be generated with the user given data and the image. I can successfully serialize the data but failed to get image in my pdf. I am using simple ajax post method to post data. Below is my code.
HTML code
<form onsubmit="submitMe(event)" method="POST" id="cform">
<input type="text" name="name" placeholder="Your Name" required>
<input type="file" name="pic" id="pic" accept="image/*" onchange="ValidateInput(this);" required>
<input type="submit" value="Preview"/>
</form>
Jquery code
function submitMe(event) {
event.preventDefault();
jQuery(function($)
{
var query = $('#cform').serialize();
var url = 'ajax_form.php';
$.post(url, query, function () {
$('#ifr').attr('src',"http://docs.google.com/gview?url=http://someurl/temp.pdf&embedded=true");
});
});
}
PHP code
<?php
$name=$_POST['name'];
$image1=$_FILES['pic']['name'];
?>
Here I am not getting image1 value. I want to get the url of the image.
You need FormData to achieve it.
SOURCE
Additionally, you need to change some stuff inside ajax call(explained in link above)
contentType: false
cache: false
processData:false
So the full call would be:
$(document).on('change','.pic-upload',uploadProfilePic);
#.pic-upload is input type=file
function uploadProfilePic(e){
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
$.ajax({
type:"POST",
url:"uploadpic.php",
data: actual,
contentType: false,
cache: false,
processData:false,
dataType:"json",
success: function (response){
#Maybe return link to new image on successful call
}
});
}
Then in PHP you handle it like this:
$_FILES['file']['name']
since you named it 'file' here:
actual.append('file', newpic[0]);

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
$('#fileToUpload').on('change', function() {
var myFormData = new FormData();
var file = document.getElementById('fileToUpload').value;
var gid = document.getElementById('gid').value;
var user = document.getElementById('user').value;
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
});
$.ajax({
url: 'imgupload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
</script>
On imgupload.php I get the POST data like this
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. What's wrong here?
FormData.append() takes key-value pairs, so this is wrong:
myFormData.append(file,gid,user);
You need something like:
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
Appart from that you need to put this code inside an event handler so that it triggers when you need it to.
For example:
$('#fileToUpload').on('change', function() {
// your javascript code
});
And you should probably also put it inside a document.ready block.

How do I add additional POST parameters to ajax file upload?

I'm using ajax file upload javascript and php script to upload an image. It works satisfactorily with $_FILES but I need to send some additional data to the processing script. The form HTML looks like:
<form id="image1" action="" method="post" enctype="multipart/form-data">
<label>image 1?</label>
<p><input type="file" class="saveImage" name="image1" value="<?php echo $something; ?>" id="<?php echo $id; ?>" additional_info="some data" /></p>
<p> <input type="submit" value="Upload" class="submit" /></p>
</form>
I need to be able to pass a variable id and some other data, call it "additional_data" to the php script, then process it in my php script using $additional_data = $_POST['additional_data']. The javascript I'm using is:
<script>
$(document).ready(function (e) {
$("#image1").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var DATA=$(this).val();
var ID=$(this).attr('id');
var ADDL=$(this).attr('additional_data');
var dataString = 'image1='+DATA+'&id='+ID+'&additional_info='+ADDL;
$.ajax({
url: "uploadFile.php",
type: "POST",
// data: new FormData(this),
data: new FormData(this,dataString),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
It doesn't send the dataString, only the FILES array.
I also wanted to do the same thing.
Here's my solution :
The JS part :
var file_data = this.files[0];
file_data.name = idaviz +'.pdf';
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append('extraParam','value231');
console.log(file_data);
console.log('here');
var oReq = new XMLHttpRequest();
oReq.open("POST", "ajax_page.php", true);
oReq.onload = function (oEvent) {
if (oReq.status === 200) {
console.log('upload succes',oReq.responseText);
} else {
console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
}
};
oReq.send(form_data);
});
The PHP part:
echo $_REQUEST['extraParam']; //this will display "value231"
var_dump($_FILES['file']); //this will display the file object
Hope it helps.
Addition info about extra parameters on formData can be found
here!
I hope I understand you right. Maybe this snippet helps you:
var formData = new FormData();
formData.append("image1", fileInputElement.files[0]);
formData.append("ID", ID);
formData.append("ADDL", ADDL);
And then set this formData variable as data:
type: "POST",
data: formData,
contentType: false,

Categories

Resources