Can't upload multiple files PHP - javascript

I have a problem. I want to be able to upload one or more files from html and then with ajax and php to save them on my server. If i just want to upload one file, it works fine, but if I want to upload more than one it doesn't work. The thing is, i have a table with 4 options and the last one is upload. But there is an ADD button under that, so when I click on that button another table (the same table) apperas, and there is where I have the problem.
This is the HTML code part:
<table id="myTable" class=" table order-list">
<tbody id="personalInfo">
<tr>
<td class="col-sm-2">
<input type="text" class="form-control" name="name0"
placeholder="<?php echo $translate['name'][$lang]?>">
</td>
<td class="col-sm-2">
<input type="text" class="form-control" name="surname0"
placeholder="<?php echo $translate['surname'][$lang]?>">
</td>
<td class="col-sm-2">
<input type="text" class="form-control datepickerYear" name="age0" autocomplete="off"
placeholder="2000" required />
</td>
<td class="col-sm-2">
<div class="pt-1">
<input type="file" class="form-control" id="UploadFile" name="UploadFile0" accept="application/pdf" required />
</div>
</td>
<td class="col-sm-1"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-danger " id="addRow"
value="<?php echo $translate['add'][$lang]?>" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
Okey and then I use JS to add another row when I click the ADD button. Everything works fine, but with the file I do this:
var fileCounter = 0;
const fileSelector2 = document.getElementById('UploadFile');
var file2;
fileSelector2.addEventListener('change', (event) => {
file2 = event.target.files[fileCounter];
fileCounter++;
});
And then with JS i use ajax to send it a POST to php.
The php part is this:
$name=$json->fullName ;
$location = "../location/" .$name.$cont. ".pdf";
if (!move_uploaded_file($_FILES['file2']['tmp_name'], $location)) {
echo json_encode(-1);
exit();
}
Like I said, when I just upload one file, it works fine, but with more than one file I don't know how to save t and use POST with multiple files.

The following code allows you to upload multiple files..
HTML:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
Javascript:
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function(response){
alert(response); // display response from the PHP script, if any
}
});
});
});
PHP (upload.php):
<?php
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $_FILES['files']['name'][$key]; // get the file name of the uploaded file
}
}
?>

Related

pass value from input=file within a jquery submitHandler [duplicate]

This question already has answers here:
how to do file upload using jquery serialization
(7 answers)
Closed 6 years ago.
I have created a form which takes certain input fields and allows a user to upload a file. The form rows are dynamically added by the users. I have used the jquery validation plugin with my form for validation purposes
The problem is i am unable to get the files which has been selected by the users. but all the other fields are being passed.
HTML
<form id="upload">
<table class="dd" width="100%" id="data">
</table>
<input name="sub" type="submit" value="Submit values"/> <input type="button" id="addnew" name="addnew" value="Add new row" />
</form>
JavaScript
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year[]" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week[]" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"> </td><td colspan="2"> </td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual[]" type="text" /></td><td width="7%">PDF</td> <td width="3%">: <input id="uploadfile1" name="userfile[]" accept="application/pdf" class="btn btn-next upload" type="file" required></td></tr>';
$('#data').append(strToAdd);
});
$("#upload").validate({
submitHandler: function (form) {
$.ajax({
url: '<?php echo base_url(); ?>/ajax_upload',
type: 'POST',
data: $(form).serialize(),
success: function(data) {
if(data){
alert("success");
} else {
alert("error");
}
},
error: function(data){
alert("error");
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});
I have made a test fiddle
Any help will be appreciated.
make the form tag as follows
<form id="upload" action="#" method="POST" enctype="multipart/form-data" >
hope this works
You are not using enctype with form
try
<form id="upload" action="#" method="POST" enctype="multipart/form-data">

AJAX - on button click does not work

as title suggests, I am having issues running my script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#subbut").click(function(e){
e.preventDefault();
$.ajax(
{
url : 'http://jsonplaceholder.typicode.com/users?email=Sincere#april.biz',
method : 'GET'
})
.then(
function(data) {
document.getElementById("street").value = data[0].address.street;
});
});
});
</script>
And my form is here:
<form id="myForm"
action="<%=response.encodeURL(request.getContextPath()
+ "/upisKorisnika.html")%>"
method="POST">
<table id='userInput' class="display" border="0"
style="font-family: Arial; font-size: 18px;">
<tr>
<td><c:out value="E-mail: " /></td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<input type="submit" name="subbut" class="btn btn-default" id="subbut" value="Submit">
</td>
</tr>
</table>
<input type="hidden" id="street" name="street" />
</form>
My first question is why doesn't anything happen when I click submit, what am I doing wrong?
And I would also like to know how could I get value of text field "Email", so I could use something like this:
url : 'http://jsonplaceholder.typicode.com/users?email='+mail,
First, is confusing the use of a form that not send data to the server and a submit button without submit form behavior.
Second you need use a debug tool like chrome developer tool. It will give you the trace of your calls.
To debug, add to the promise.then the error callback with a simple alert or a console.log to view what is happen with your call.
And responding your question,your code seen be right.

How to transfer json strings back and forth between HTML and PHP via jQuery Ajax?

Hi I'm new to PHP and jQuery and I was doing some tests trying to figure out how things work. But I keep having trouble transferring data back and forth between my web page and the php file on the server. Here is the code:
<center>
<form>
<hr>
<table style="width:80%;border:3px;">
<tr>
<td align="center"><input type="text" id="name" placeholder="First Last"></td>
<td align="center"><input type="text" id="ssn" placeholder="First Last"></td>
<td align="center"><input type="text" id="birth" placeholder="First Last"></td>
<td align="center"><input type="text" id="xxxx" placeholder="First Last"></td>
<td align="center"><button type="button" id="add">Add</button></td>
<script>
$("#add").click(function() {
var nameIn = $('#name').val();
var ssnIn = $('#ssn').val();
var birthIn = $('#birth').val();
var xxxxIn = $('#xxxx').val();
xxxxIn = "\$" + xxxxIn;
$.ajax({
type:"POST",
url:"database_update.php",
dataType:"JSON",
data: {
name: nameIn,
ssn: ssnIn,
birth: birthIn,
xxxx: xxxxIn
},
success: function(ret) {
var out = JSON.stringify(ret);
alert(out);
}
});
});
</script>
</tr>
</table>
</form>
</center>
<?php
$name = $_POST['name'];
$ssn = $_POST['ssn'];
$birth = $_POST['birth'];
$xxxx = $_POST['xxxx'];
header('Content-type: application/json');
if (isset($name))
{
$ret = array(
"name" => $name,
"ssn" => $ssn,
"birth" => $birth,
"xxxx" => $xxxx
);
echo json_encode($ret);
} ?>
The alert function was never triggered and the response from php was successful.
Although it seems a little unlikely that anyone will stumble across this post with the exact same issue, I'll post an answer with the essence of the comments.
1) Remove white space from PHP tags "<?php", not "<? php"
2) Include jQuery in your tag (you already had this done)
3) Make sure files are in the same directory, or include the directory path in your AJAX call (you were fine here, too)
4) Verify the Response in the Network tab of the Chrome Console or Firebug. No PHP should ever be visible here.
5) Reduce complexity as much as possible. Once it is working, gradually add code back in.

Issue with multipart/form-data, ajax and textarea with TinyMCE

I'm working with html/php/ajax/jquery and today I pointed out a little issue that is driving me crazy.
I've got an html form:
<form method="POST" enctype="multipart/form-data" name="myForm" id="myForm" action="">
<label class="form-label">Nome</label>
<input name="nome" type="text" class="form-control"><br>
<label class="form-label">Descrizione</label>
<textarea name="descrizione" id="text-editor" placeholder="" class="form-control" rows="10"></textarea>
<label class="form-label">Stato</label>
<select name="stato" id="source" style="width:30%">
<option value="1">Abilitato</option>
<option value="0">Disabilitato</option>
</select>
<h4>Foto profilo</h4>
<input type="hidden" name="MAX_FILE_SIZE" value="20400000" >
<input style="border:0px;" type="file" name="user_foto" id="file">
<div class="form-actions">
<div class="pull-right">
<button type="submit" class="btn btn-success btn-cons"><i class="icon-ok"></i>Inserisci</button>
<button type="button" class="btn btn-white btn-cons" onclick="window.location.href='index.php'">Indietro</button></a>
</div>
</div>
</form>
I'm working with a JQuery+Ajax script that is able to fire a php script without reloading page, and insert form's data into a table in my database:
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
var formData = new FormData(this);
$.ajax({
url:'inserisciProfessionisti.php',
data: formData,
type:'POST',
async: false,
cache: false,
contentType: false,
processData: false,
success:function(data){
window.location = 'listaProfessionisti.php'
},
error:function(data){}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
Here my php code:
<?php
session_start();
session_cache_limiter('nocache');
if(!isset($_SESSION['mail'])){
header("location:login.php");
}
include("include/connect.php");
$conn=mysql_connect($HOST, $USER, $PASSWORD);
$db_ok=mysql_select_db($DB, $conn);
$nome=$_POST['nome'];
$descrizione = $_POST['descrizione'];
....
$comando="INSERT INTO professionisti('nome','descrizione',...)VALUES('$nome','$descrizione',...)";
$ris=mysql_query($comando, $conn) or die("Errore connessione database: " . mysql_error());
...
Everything works like a charm apart textarea content. It seems that textarea content wouldn't be passed to my php script.
Issue solved.
I add this onclick="tinyMCE.triggerSave(true,true);" to submit button and everything works like a charm.
I think It should be a tinyMCE bug.

Uploading file in a form without page refresh

I have this bit of code:
<form name="myUploadForm" method="post" action="/scripts/upload.do" enctype="multipart/form-data" id="fileUpload">
<table width="100%" border="0">
<tr>
<td>
<input type="file" name="xlsFile" size="60" value="test.xls">
<input type="button" value="Upload File" name="upload_xls">
</td>
</tr>
</table>
</form>
Right now I can upload the file with Struts but it refreshes the page. How do I do this without the page refreshing?
What worked for me:
On the form tag, I have target="hidden-iframe"
the hidden i-frame on the page looks like this:
<iframe name="hidden-iframe" style="display: none;"></iframe>
The important thing to underline here is that the form is referencing the name attribute of the frame and not the id.
You can post form with jQuery and get the result back.
$('#formId' ).submit(
function( e ) {
$.ajax( {
url: '/upload',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(result){
console.log(result);
//$("#div1").html(str);
}
} );
e.preventDefault();
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formId" action="/upload" enctype="multipart/form-data" method="post">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
<div id="div1">
</div>
There are two methods:
HTML5 supports File API.
Create a hidden iframe, point the property 'target' of the form to the iframe's id.
If you can use jQuery, you can use something like jQuery File Upload.

Categories

Resources