multiple input file upload using ajax - javascript

I have multiple input fields of type file generated using php foreach loop.Below is a snippet html form generated
<input name="userImage" id="a1Cym4V" type="file" />
<button type="button" onclick="upload_proof('a1Cym4V')">Upload</button>
<input name="userImage" id="pe7h6Cx" type="file" />
<button type="button" onclick="upload_proof('pe7h6Cx')">Upload</button>
<input name="userImage" id="L9iCaxV" type="file" />
<button type="button" onclick="upload_proof('L9iCaxV')">Upload</button>
If i upload an image using the first input form, it works fine, all others will return empty value even when a file is selected.
This is the javascript code i use to process the file upload via ajax.
function upload_prooff(id){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
formData.append('id', id);
formData.append('upload_proof', '1');
$.ajax({
url: "convert.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
}
The data contains var_dump($_FILES) from the server.
What is the best approach to solve this problem?

Related

How to avoid move_uploaded_file() refresh the page on button click

I am using $.ajax({}) of jQuery, I am trying to move the uploaded file in folder on click. The upload came successful but my problem is when uploading, the page is refreshing I already tried e.preventDefault() and <button type="button">
This is my html code
<input type="file" id="student-img-file" accept="image/*" name="student-img-file">
<button type="button" id="btn-submit-form" class="mt-4">Submit Form</button>
This is my jQuery code
$('button#btn-submit-form').on('click', function(e){
let formData = new FormData()
formData.append('student-img-data', $('#student-img-file').prop('files')[0])
$.ajax({
url: '../PHPFunctions/AdmissionFormFunction.php',
method: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(result){
console.log(result)
}
})
})
this is my PHP(AdmissionFormFunction.php) code
$studentImgData = $_FILES['student-img-data'];
if(move_uploaded_file($studentImgData['tmp_name'], '../FileUploads/' . $studentImgData['name'])){
echo "YESSSSSSSSSSSS";
}
I am not using form tags by the way
I just turned off my vs code live server. I forgot that any changes that i've made in my folder system in vs code will refresh the page.

Post more than one parameter for file upload to the web api

I have this html form which let user upload a file and also another extra input type for extra info about this upload.
<form method="post" enctype="multipart/form-data">
<input id="files" name="files" type="file" size="1" />
<input type="text" id="tags">
<button type="submit" id="btnSave" onchange="uploadFiles();">Upload and Save</button>
</form>
and this is my javascript
function uploadFiles() {
var input = document.getElementById('files');
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "https://localhost:xxx/api/file/upload",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function () {
alert("Files Uploaded!");
}
}
);
}
My question is how do I add others parameters (i.e tags here) to post to web api and at the same time upload the file? Post the request at complex type? Any example for complex type which include file upload?
You just can append new properties there.
formdata append will help you to add string and file
formData.append("tags",document.getelementbyid('tags').value);
this is some source to read about FormData
https://developer.mozilla.org/en-US/docs/Web/API/FormData

Multiple file upload using ajax in wordpress

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.

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

Categories

Resources