How to submit a form with file uploads with ajax - javascript

I have a long multistep form. which have text inputs and an upload file option. I'm trying to submit it to PHP with Ajax. I have tried FormData but I'm not sure how to send other select and text input fields.
https://developer.mozilla.org/en-US/docs/Web/API/FormData
How can I do this?
const addListingForm = $('#add-listing-form');
addListingForm.on('submit', function (e) {
console.log('Submitted');
const formData = new FormData(document.getElementById('add-listing-form'));
$.ajax({
url: `${SITE_URL}/private/shared/process`,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (resp) {
console.log(resp);
},
error: function (err) {
console.log(err);
},
});
e.preventDefault();
});
<form action="" method="post" enctype="multipart/form-data" id="add-listing-form">
<input type="text" name="title" id="title" class="custom-input" />
<input type="text" name="tagline" id="tagline" class="custom-input" />
<input type="file" name="halal-certificate" class="custom-file-input" id="halal-certificate">
<input type="file" name="list-photos[]" multiple class="custom-file-input" id="list-photos">
<button type="submit">
Submit
</button>
</form>

try this
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0];
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
//and add more
or
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
req.open("POST", '/upload/image');
req.send(formData);

Related

Php Ajax file upload, always getting undefined index error

Submitting file through ajax not working. I have followed other posts to create this but it appears formdata is not containing the file as a result i always get the error of undefined index 'image'
<form enctype: 'multipart/form-data'>
<div class="add_category">
<label style="font-size:20px;">Add categories</label>
<input type="text" name="category" id="category" placeholder="Enter Here" style="border-style:solid;height:30px;">
<label style="font-size:20px;">Choose image</label>
<input type="file" id="file" name="image" style="border-style:solid;height:25px;">
<button name="add_category" type="button" onclick="addcategory()" >ADD Category</button>
</br>
</br>
</div>
</form>
function addcategory(){
//var1=document.getElementById("category").value;
var formData = new FormData();
formData.append('image', $('input[id=file]')[0].files[0]);
$.ajax({
url : 'performcategoryserver.php',
type : 'POST',
enctype: 'multipart/form-data',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
alert(data);
}
});
}
performcategoryserver.php:
<?php
$imagename=$_FILES['image']['name'];
echo($imagename);
?>
This always return undefined index image error ,please help.
Change
<form enctype: 'multipart/form-data'>
to
<form id="myform" enctype= 'multipart/form-data'>
Change your function to:
function addcategory(){
var formData = new FormData( $("#myform")[0] );
$.ajax({
url : 'performcategoryserver.php',
type : 'POST',
data : formData,
async : false,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType:"json",
success : function(data) {
alert(data);
}
});
}
Your form tag opened in wrong way firstly can you fix that and try again ?
<form enctype: 'multipart/form-data'>
Should be
<form method="post" enctype="multipart/form-data">
Finally found the working code,
Changed this:
<form id="myform" enctype= 'multipart/form-data'>
Changed this:
function addcategory(){
var formData = new FormData( $("#myform")[0] );
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'performcategoryserver.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
alert(xhr.responseText);
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
}

How to submit two forms with their Ajax with one button

I have two forms one with product details like price, description and name. And the other with images, they both have different Ajax but they send data to the same route. I want to submit them with one button. So if I click a submit button it should submit all data at once which are price, name, image etc. How can I do this if possible?
Blade file
//Form1
<form id="form1">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name"
placeholder="Enter product name">
<label for="price">Price</label>
<input type="text" class="form-control" name="price" id="price"
placeholder="Enter product price">
</form>
//Form2
<form id="file_form" method="post" enctype="multipart/form-data">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="images">Choose Images</label>
<input id="files" type="file" class="" name="files[]" multiple />
</form>
//Submit Button
<input type='button' class="btn btn-primary" value="Submit" id="btn"/>
Javascript
//Form1 javascript
var token = $("#token").val();
$(document).ready(function(){
$("#btn").click(function(){
var url = '{{ route('product.store') }}';
var form = $('form')[0];
var formData = new FormData(form);
formData.append('_token', token);
$.ajax({
url: url,
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success:function(data){
if($.isEmptyObject(data.error)){
$("#msg").html("Product has been added successfull");
$("#msg").fadeOut(3000);
}
}
});
});
//Form 2 Javascript
$("#btn").click(function (e) {
e.preventDefault();
file_area = $('.file-area');
progressbar = $('.progress-bar');
status_bar = $('#status');
image_list = $(".image-list");
status_bar.css('display', 'block');
status_bar.html('<div class="fa-3x">' +
'<i class="fas fa-spinner fa-pulse"></i>' +
'</div>');
if (selected_files.length < 1) {
status_bar.html('<li class="error">Please select file</li>')
} else {
var data = new FormData();
data.append('_token', token);
for (var i = 0, len = selected_files.length; i < len; i++) {
data.append('files[]', selected_files[i]);
}
fiel_feild = $('#files');
$.ajax({
url: '{{ route('product.store') }}',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false,
success: function (response) {
result = JSON.parse(response);
if (result['status'] == 'error') {
status_bar.html(result['error']);
} else if (result['status'] == 'success') {
selected_files = [];
image_list.html('');
file_area.css('display', 'none');
status_bar.html('<li class="success">File uploaded successfully.</li>');
}
}
});
return false;
}
});

Upload a file with Ajax, jQuery and Laravel [duplicate]

This question already has answers here:
How to upload a file using jQuery.ajax and FormData
(2 answers)
Closed 3 years ago.
I am trying to upload a form with jQuery and Ajax using Laravel as server side code, my form is:
HTML:
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Comprobante</label>
<input type="file" name="file" class="form-control" id="file" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nombre</label>
<input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name">
</div>
</form>
jQuery, Ajax:
$( 'body' ).on( "submit", 'form', function() {
event.preventDefault();
var formData = new FormData();
formData.append("file", $('#file')[0].files[0]);
formData.append("name", $('#name').val());
var formData = $(this).serialize();
$.ajax({
type:'POST',
url:"{{ url('/accountability/store') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
success:function(html)
{
alert('stored!');
}
});
});
Laravel:
$extension = $request->file('file')->getClientOriginalExtension();
$filename = $request->rut.'_rendicion_'. date('d_m_Y_h_i_s') .'.'.$extension;
Storage::disk('dropbox')->putFileAs(
'/intranet_jisparking_archivos_web/',
$request->file('file'),
$filename
);
The problem is that it says that
Call to a member function getClientOriginalExtension() on null
But I do not understand why? because I am uploading the file with this $('#file')[0].files[0] in the jQuery. It looks like $request->file('file') is empty, how can I fix it?
Thanks!
Try this:
var formData = new FormData();
var file = $('#file').prop('files')[0];
formData.append('file', file);
formData.append('other_variable', $('#other_variable').val());
// Don't use serialize here, as it is used when we want to send the data of entire form in a query string way and that will not work for file upload
$.ajax({
url: '{{ url("your_url") }}',
method: 'post',
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
// Do what ever you want to do on sucsess
}
});
In controller method, you will get the file like:
$file = Input::file('file');

Uploading file to Slack API files.upload with jquery

I'm trying to, on a webpage, select a file and post it in Slack via the Slack API.
I was originally doing:
var request = require('request');
$(".submit").click(function(){
request.post({
url: 'https://slack.com/api/files.upload',
formData: {
token: "myTokenHere",
title: "Image",
filename: "image.png",
filetype: "auto",
channels: "mychannel",
file: document.getElementById('idofuploadelement').files[0]
},
}, function (err, response) {
console.log(JSON.parse(response.body));
});
So then I switched to trying Ajax so that I don't have to include require.
$(".submit").click(function(){
$.ajax({
type: "POST",
method: "POST",
enctype: "multipart/form-data",
url: 'https://slack.com/api/files.upload',
formData: {
token: "myTokenHere",
title: "Image",
filename: "image.png",
filetype: "auto",
channels: "mychannel",
file: document.getElementById('idofuploadelement').files[0]
}
}).done(function(url) {
console.log(url);
});
});
but this gives me the console warning
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent.
Even though I have those properties (I got the error before adding them too), I still get the error.
My html is simple html5 input tags (for upload and submit button)
<input type="file" name="fileToUpload" id="idofuploadelement">
<input type="submit" name="submit" class="submit action-button next" value="Next"/>
In a nutshell, I'm trying to get a file sent to me (in any way, Slack, Github, email, whatever) without having to spin up a server. Is it possible?
Figured it out:
HTML:
<form id="myform" method="POST" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="file-select">
<input id="upload-button" type="submit" name="submit" class="submit action-button next" value="Next"/>
</form>
JS:
var form = document.getElementById('myform');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
var file = fileSelect.files[0];
var formData = new FormData();
formData.append('file', file, file.name);
formData.append('token', insert_token_here);
formData.append('channels', insert_channel_here);
var xhr = new XMLHttpRequest();
xhr.open('POST','https://slack.com/api/files.upload', true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
uploadButton.innerHTML = 'Uploaded';
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
}

Simple FormData not working

I am trying to test a simple FormData object but its not working at all. jsfiddle: https://jsfiddle.net/8j80898h/
html code:
<form id="createForm" name="createForm" novalidate enctype="multipart/form-data">
<input type="hidden" name="name" value="Name1" />
<input type="file" name="file" />
<input type="button" id="submitIt" value="Submit" />
</form>
js:
$(document).ready(function() {
$('#submitIt').click(function() {
var fd = new FormData($('#createForm')[0]);
fd.append( 'name', $('input[name=name]').val());
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
});
Server is always getting null values for name and file
FormData has a get method you should use:
$(document).ready(function() {
$('#submitIt').click(function() {
var d = new FormData($('form')[0]);
alert(d.get('name'));
});
});
read more in MDN: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get
rather than making an FormData object you can access elements within an form like the code below shows :)
$(document).ready(function() {
$('#submitIt').click(function() {
var d = $('form').toArray();
alert(d[0].name);
});
});

Categories