How to upload multiple image upload without submit button using ajax jquery? - javascript

How to upload multiple image upload without submit button using ajax jquery?Can someone help my finding out whats wrong?
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
Here is the code
<body>
<input name="files[]" type="file" multiple />
<input type="hidden" name="hiddenval" id="hiddenval" value="">
<button id="upload" value="Upload" class="btn btn-success" />
</body>
</html>
<script>
$(document).on("click", "#upload", function() {
var outputdata = [];
$.ajax({
url: "upload1.php",
type: "POST",
data: new Form(this),
contentType: false,
processData: false,
success: function(files, data, xhr) {
outputdata.push(files);
$('#hiddenval').val(outputdata)
}
});
});
</script>

add id to this input for easier get value.
<input name="files[]" type="file" multiple id="files"/>
Includes values from this input to data:
$(document).on("click", "#upload", function() {
var outputdata = [];
var fileSelect = document.getElementById('files');
var files = fileSelect.files;
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('photos[]', file, file.name);
}
$.ajax({
url: "upload1.php",
type: "POST",
data: formData,
contentType: false,
processData:false,
success: function(files,data,xhr)
{
outputdata.push(files);
$('#hiddenval').val(outputdata);
}
});
});
Refer: http://blog.teamtreehouse.com/uploading-files-ajax

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.

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.

How to upload image with all entered textbox value using AJAX in asp.net MVC 5 without Form or Beging form tag?

I don't want to reload my page so i am using AJAX, here Index.cshtml page for image uploading with text box. This code is currently working but i want to pass data from cshtml page to controller side using of ajax without form tag.
<form class="form-horizontal" id="fc" action="#Url.Action("SaveAcademy", "Academy")" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
<input type="text" class="form-control" onblur="checktxtvalidation(this.id)" name="txtacademyname" id="txtacademyname">
<input type="file" class="form-control" name="fileupload" id="fileupload" multiple="multiple">
<input type="submit" value="submit" id="submit" name="submit" class="btn btn-block btn-primary" />
</form>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveAcademy(HttpPostedFileBase fileupload, FormCollection fc)
{
....
.... here are some code for inserting data into database
....
}
<input type="file" class="form-control" name="fileupload" id="fileupload" >
it is not need to be in form tags.
<script type="text/javascript">
$('#fileupload').on('change', function (e) {
var files = e.target.files;
var text=$('#txtacademyname').val();
if (files.length > 0) {
var data = new FormData();
data.append("file", files[0]);
data.append("acatext", text);
console.log(data);
$.ajax({
type: "POST",
url: '#Url.Action("SaveAcademy","Academy")',
contentType: false,
processData: false,
data: data,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
});
You can use a button to trigger upload or like my demo just use change event.And if you do not add processData: false to prevent automatic processing , you will get 'Illegal Invocation'.
[HttpPost]
public ActionResult SaveAcademy(HttpPostedFileBase file, string acatext)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var location = Path.Combine(
Server.MapPath("~/Images"), fileName);
file.SaveAs(location);
return Json("File uploaded"+acatext);
}
else
{
return Json("Failed");
}
}
removed [ValidateAntiForgeryToken] if you want it , then you have to add it manually to your ajax header.
EDIT to make it work button click
add button to page <input type="button" value="upload" id="upload" /> ,register click event
<script type="text/javascript">
$('#upload').on('click', function (e) {
var fileform = document.getElementById('fileupload');
var files = fileform.files;
var text=$('#txtacademyname').val();
if (files.length > 0) {
var data = new FormData();
data.append("file", files[0]);
data.append("acatext", text);
console.log(data);
$.ajax({
type: "POST",
url: '#Url.Action("SaveAcademy","Academy")',
contentType: false,
processData: false,
data: data,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
});
</script>
Check this out
http://www.c-sharpcorner.com/UploadFile/b696c4/how-to-upload-and-display-image-in-mvc/
I hope it will be useful for you.

Uploading multiple files with Ajax not making POST

I took an example of How can I upload files asynchronously? which is a great example BTW.
For some reason my POST is not making it to my php file. Even when I print_r($_POST) the array comes up blank. I am trying to pass 2 fields with this Script.
If I simple do an echo "test"; on my php file it will return that string.
I also tried var formData = new FormData($('form').serialize());
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'inserttest.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;
},
success: function(data) {
alert(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
</script>
</head>
<form enctype="multipart/form-data">
<input type="text" name="words" id="words" />
<input name="file" type="file" id="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
Took it a step further and made it the long way with formData...still no luck
var words = $('#words').attr('value');
var file = $('#file').attr('value');
var formData = new FormData();
formData.append("words", words);
formData.append("file", file);
inserttest.php
Tried
<?php
echo print_r($_POST);
?>
and
<?php
echo print_r($_FILES);
?>
the Jquery version you're using is outdated and doesn't support this feature!
Change version 1.3.0:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
...to version 1.9.1:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
...and it works!! :D

Categories

Resources