Retrieve file uploaded in Laravel using JavaScript FormData - javascript

Running into a bit of trouble trying to upload multiple files through a single AJAX request into a Laravel 5 back-end.
In the front-end, I am using the following code to prep the FormData object:
var fd = new FormData();
fd.append("data", JSON.stringify(values));
fd.append("page_id", page_id);
files.forEach(function(file, index){
fd.append("file_"+index, file);
});
Then this is my AJAX call:
$.ajax({
type: 'POST',
url: '/file_test',
data: fd,
contentType: false,
processData: false,
success: function(response){
alert(response);
},
failure: function(response){
alert(response);
}
});
In the back-end, I've tried to retrieve with $request->allFiles() and $request->file('file_0') as well as $_FILES but they are all turning up empty.
After #Pavel mentioned that the $_FILES array was empty, I went and checked what was being sent up in the XHRRequest. What I realized was that I was not appending the file itself to the FormData object and instead was appending the whole input containing the file.
var files = [];
if(this.type == "file"){
if(this.files.length == 1){
values[$(this).attr('name')] = this.files[0].name;
//files.push(this); // ORIGINAL CODE
files.push(this.files[0]); // WORKING CODE!
}
}

Related

How can I combine two ajax functions in one function?

I have ajax code which can post name and I have another ajax which can post image I need to combine those two functions in order to have one function which can post both name and image
Below codes used to post image
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
And below codes used to post name
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
$.ajax({
type:"post",
url:"upload.php",
data:
{
'name' :name
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
How can I combine above codes in order to use only one url "upload.php", this means upload.php will insert name in database and save image in folder while click save button, that's why I need to combine the codes
Please anyone can help me
You literally combine them.
You can use your first function and do the following:
var fd = new FormData();
var files = $('#file')[0].files;
fd.append('name', $("#name").val();
that is it. And on the other side (backend) you just ask for this name:
$name = $_POST['name'];

How to Clear/Reset formData() using javascript?

I am using formData for Ajax Image Uploading, when I am submit first time it will successfully upload, and again click post button that image also posted to server, I think formData will not clear.
My Code
$("#postsubmitimage").click(function () {
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
if (files[i].type.indexOf('image/') === 0) {
formData.append("files", files[i]);
}
}
$.ajax({
type: "POST",
url: '/Ajax/Fileupload/',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (json) {
$('#textpostimage').val('');
}
});
})
I think this happens because your files variable is not cleared after the ajax submission. In your click handler you create an empty FormData object indeed, but then you proceed to fill that object with old references from files, which apparently are not clear.
What I suggest is doing some cleanup after a successful ajax completion
success: function (json) {
// Supposing #textpostimage is your file input, you are already clearing it
$('#textpostimage').val('');
// Also clear your "files" reference
files = [];
}
To clear the whole form you could do $('#myForm').get(0).reset()
I don't know at what time you populate files with values from #textpostimage, but make sure to do it not only on page load, if you want to have multiple form submissions working.
Have you tried doing it this way?
var formData = new FormData($('<form></form>'));

Undefined index error when trying to echo input text in PHP?

I am trying to echo the contents of an input field on enter. I have a text input field that I create here:
echo '<form id="changePassForm" action="" method="post" enctype="multipart/form-data">
<div class="changePass">
<div class="changePassBtn">Change Password</div>
<input class = "passwordText" type="password" placeholder="Password" name="passwordText">
</div>';
The field calls this javascript function correctly:
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
datatype: 'text',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
Which references password change.php here:
<?php
session_start();
echo "Hello world";
$pass=$_POST['passwordText']; //name of input
echo $pass;
/*$dbh = new PDO("mysql:host=localhost;dbname=sqlserver", 'username', 'password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkforpass = "SELECT password FROM sqlserver.accounts WHERE username='".$username."'";*/
?>
I'm not versed in PHP but Hello world is output to console. How can I output/store value of text field in $pass?
Untested, off the cuff:
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
var pass = $('#changePassForm input').val();
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: 'passwordText=' + pass, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
Note also that it is dataType: not datatype:, and that dataType only affects returning data not data being sent to PHP
So, get it working simply first (as above), then get fancy with $('#changePassForm').serialize() etc.
Try as follows
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
var postData = $('#changePassForm').serializeArray();
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: postData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
datatype: 'text',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
If you want to use FormData, you can see from the manual that the FormData object constructor takes an optional <form> element and you're using this, which refers to $(".passwordText"), which is a jQuery object. You can pass a form element by doing:
var form = document.getElementById("changePassForm");
var fd = new FormData(form);
Putting this all together we would then have:
$(document).ready(function() {
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
event.preventDefault();
var form = document.getElementById("changePassForm");
var fd = new FormData(form);
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: fd, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
dataType: 'text',
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
});
As an alternative you can manually append any values you want to have sent in the ajax request like this:
var fd = new FormData();
fd.append($(this).attr("name"), $(this).attr("value"));
Disclaimer:
With that said, the FormData interface is only available in IE >= 10, so if you are worried about cross browser compatibility you may want to consider simply using jQuery's serialize() method to send the data. As an added bonus, it's only 1 line of code.:
data: $("#changePassForm").serialize()

i can't upload images using Ajax

I've been trying to add a new product using ajax and bootstrap (modal) and when I press the save changes button, I get Undefined index in all the fields.
Here's my ajax code:
$('#save').click(function(){
var nombre = $('#nombre').val();
var desc = $('#desc').val();
var precio = $('#precio').val();
var stock = $('#stock').val();
var tipo = $('#tipo').val();
var data = new FormData();
jQuery.each(jQuery('#imagen')[0].files, function(i, file) {
data.append('file-'+i, file);
});
var datas="nombre="+nombre+"&desc="+desc+"&precio="+precio+"&stock="+stock+"&tipo="+tipo;
$.ajax({
url: "php/newproduct.php",
data: {datas, data},
cache: false,
contentType: false,
processData: false,
type: "POST"
}).done(function( data ) {
$('#info').html(data);
viewdata();
setTimeout(function() {
$('#myModal').modal('hide');
}, 500);
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
});
});
data: {datas, data},
doesn't seem to be proper javascript syntax and I don't think you can mix different data object.
You can't mix FormData and an URL encoded string, which in your case isn't event properly encoded and you will have problems, if any of the values contains &.
The easiest way to upload using AJAX would be, if you initialized the FormData object with your form
var data = new FormData($("#form").get(0));
and then just used
data: data,
in your AJAX call
If you really need to add the fields manually, you need to add them to the FormData object
data.append("nombre", nombre);
data.append("desc ", desc);
data.append("precio ", precio);
data.append("stock ", stock);
data.append("tipo ", tipo);

how to get data in the success of ajax

I have the following ajax function:
reader.onload = function(event){
var fd = new FormData();
var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
console.log("name = " + Name);
fd.append('fname', Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function(data){
//console.log(data);
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName},
success: function(data){
console.log(data);
}
});
}
});
};
first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?
second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?
server-side code:
<?php
$fileName=$_POST["fileName"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;
This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.
var mySuccessVar = null;
...
success: function(data) {
mySuccessVar = data;
}
... // later in the code:
if (mySuccessVar != null) {
yourFunction(mySuccessVar);
}

Categories

Resources