form data upload multiple files through ajax together with text fields - javascript

Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
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('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!

Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
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('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']

Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input

Related

How to pass an array of "FormData" via ajax and access in Laravel controller

# I just want to know how to send this array the controller by requete ajax
var dataPanier=[];
function addarray(objser)
{
dataPanier.push(objser);
}
$('.target').click(function() {
var btn_name=$(this).attr("name");
switch(btn_name) {
case 'FormPVC':
var dataformPVC = new FormData(),
form_data = $('#'+btn_name).serializeArray();
$.each(form_data, function (key, input) {
dataformPVC.append(input.name, input.value);
});
dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
addarray(dataformPVC);
break;
.
.
.
more . . .
I am attempting to send multiple forms data as an array by ajax to a Larave controller.
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: array ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
$("#btnTest").click(function(){
var formData = $('#frm1, #frm2').serialize();
console.log(formData);
$.ajax({
method: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frm1">
<input name="n1" type="text"/>
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<form id="frm2">
<input name="n1" type="text" />
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<input type="button" id="btnTest" value="send"/>
As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:
var formData = $('#form1, #form2').serialize();
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div>.

Sending a File (PDF) through ajax to a JSP Servlet

I am trying to send two PDF Files )initially just one) through an HTML form using javascript (jquery or not), I have to receive both files in a controller of a JSP page (using Spring) and do something with both files.
Right now I have been trying some of the answers already posted here in SO, but I am not being able to get it to work correctly.
My HTML File
<form id="searchForm">
<table class=rightAlignColumns>
<tr>
<td><label for="File1"><spring:message code='File1' />:</label></td>
<td><input id="File1" type="file" name="File1" /> </td>
<td><label for="file2"><spring:message code='File2' />:</label></td>
<td><input id="file2" type="file" name="file2" /> </td>
</tr>
</table>
<br/>
<input type="submit" value="<spring:message code='Btn' />" />
</form>
My javascript
var fd = new FormData();
alert(document.getElementById('File1').files.length);
fd.append( 'File1', document.getElementById('File1').files[0] );
// fd.append( 'File2', document.getElementById('File2').files[0]);
$.ajax({
url:'myurl.json',
data: fd,
cache:false,
processData:false,
contentType:false,
type: 'POST',
success: function(data){
// alert(data);
}
});
On the controller I am doing what this other post said.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}
The problem I think it is in the javascript, because when the code enters to the Controller the list "items" has a size of 0, and going into the exception.
The expected result would be the user loading a PDF file into the Form, hitting submit and ajax sending the file to the server (controller), doing stuff correctly and sending back a result.
Right now the client is not uploading correctly the file.
As a side note, the file I am uploading is going to be used by pdfbox or google ocr in the controller.
Thanks in advance!
It worked using the next code:
JS:
function doAjax() {
// Get form
var form = $('#id_form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "controller/myMethod",
data: data,
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
dataType:'json',
success: function (e) {
$("#result").text(data);
alert("Success");
},
error: function (e) {
$("#result").text(e.responseText);
alert("Error");
},
complete: function () {
// Handle the complete event
alert("Complete");
}
});
}
And on the controller
#RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public String uploadFileMulti(#RequestParam("file") MultipartFile file,HttpServletRequest request) {
try {
//storageService.store(file, request);
System.out.println(file.getOriginalFilename());
return "You successfully uploaded " + file.getOriginalFilename();
} catch (Exception e) {
return "FAIL!";
}
}
My HTML file
<form class="form-horizontal" method="POST" enctype="multipart/form-data" id="id_form">
<label for="file">File:</label>
<input id="file" type="file" name="file" />
</form>

Image Upload at Google Appengine using AJAX and PHP

I'm trying to upload an image on Google appengine hosting using ajax and php and I always get server error 500
My approach is create upload url which will be later used to submit the form to:
<?php
$upload_url = CloudStorageTools::createUploadUrl('/upload_script', $options);
The form which will be submitted as soon as any change is made to the input type file:
<form <?php echo 'action="$upload_url"'; ?> enctype="multipart/form-data" method="post">
Files to upload: <br>
<input type="file" name="uploaded_files" size="40">
<input type="submit" value="Send">
</form>
Since I'm doing it using AJAX here is the ajax code:
$(document).ready(function () {
$('#form').on('submit',(function(event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(){
console.log("success");
},
error: function(){
console.log("error");
}
});
}));
$("#browse").on("change", function() {
$("#form").submit();
});
});
This produces server error 500 when looking on it in console does anyone know where might be the problem?

What about Dropzone.js within an existing form submitted by AJAX?

Ok, here is the scenario. I have already a form having some input fields, some radio buttons and an input type=file. There is a button for submitting the whole form using AJAX.
Everything was working fine, until i decided to change the input type=file with the more fancy DropZone.js
Now i have the following html code (a sample here):
<form enctype="multipart/form-data" id="test_form" name="test_form" class="form uniformForm">
<input class="form-control" type="text" value="" name="a-name" id="a-name" />
<label for="a-name">Field Name</label>
<div class="dropzone dropzone-previews" id="my-awesome-dropzone </div>
</form>
<button class="btn btn-primary btn-large" id="submitForm"> Submit </button>
I have the following js (jQuery), too:
$("button#submitForm").click(function(){
var fd = new FormData(document.getElementById("test_form"));
fd.append("label", "WEBUPLOAD");
$.ajax({
type: "POST",
url: "create_form.php",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
});
});
$("div#my-awesome-dropzone").dropzone({
url: "#",
paramName: "creative_file",
maxFilesize: 1,
autoProcessQueue: false
});
In documentation of Dropzone.js says that the dropzone div looks like <input type="file" name="file" />. The only difference is that i want to rename the input name as creative_file.
I have 2 question.
1) This doesn't work. When pressing the Submit button, i have FIREBUG opened and i check what it sends as POST. It sends everything except the files. No creative_file, no file at all.
2) If finally figured out how to make it works, is there any way to have a fallback with this implementation especially for the iOS or Android devices ?
1)
$("#salvar").on('click',function(e) {
if ($("#psl_titulo").val() == "") {
alert('Empty');
} else {
e.preventDefault();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
$("#my-awesome-dropzone").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.href = url_redirect;
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Ocorreu um erro ao salvar ao enviar os dados. Erro: ' + textStatus);
}
});
e.preventDefault();
});
$("#my-awesome-dropzone").submit();
}
}
});

Send form data with jquery ajax json

I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.

Categories

Resources