Basic jQuery Ajax file upload with PHP - php

I've been trying to get a basic file upload through an ajax form without success. I'm looking for the bare minimum basics and nothing I have found through searching has worked.
I've been messing about with this for about 8 hours and have tried at least a dozen different methods but have not been able to get anything successfully uploaded.
I have narrowed down my code to the most bare necessities as best I can.
My JavaScript goes like this:
function uploadFile(param) { //Upload File
$.ajax({
url: "modules/upload/upload.php",
type: "post",
data: new FormData($(param)[0]),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
}
});
}
which is called with:
$(".app-canvas").on('change', ".fileUpload", function () {
uploadFile($(this));
});
and the PHP:
<?php
$sourcePath = $_FILES['driver_licence_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/".$_FILES['driver_licence_image']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
?>

FormData takes an HTMLFormElement as an argument to its constructor, you're passing what looks a file input. To add a file from a form element you have to use append.
$(".app-canvas").on('change', ".fileUpload", uploadFile);
function uploadFile() { //Upload File
var fd = new FormData();
fd.append('driver_licence_image', this.files[0]);
$.ajax({
url: "modules/upload/upload.php",
type: "post",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
}
});
}
p.s. $(param)[0] is equivalent to param(when param is a dom node), so please don't do that.

Related

save an upload image in a folder without form

I want to upload an image from an input, and save it in a folder (called 'photos').
In HTML, I have a simple input type file like this:
<input type="file" name="inputFile" id="inputFile" accept="image/jpeg,
image/png">
<span>Scegli una foto</span>
<input id="Invia" type="button" value="Invia">
In Javascript, i used this AJAX call:
var myFormData = new FormData();
myFormData.append($("#inputFile")[0].files[0]['name'], $("#inputFile")[0].files[0]);
$("#Invia").click(function (){
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: myFormData,
url: "../api/photo.php",
dataType : 'json',
success: function(jsonData){}
});
});
In PHP, the '../api/photo.php' file is this:
<?php
header('Content-Type: application/json; charset=utf-8');
$destination= '../app/photos';
$tmp_name = $_FILES["inputFile"]["tmp_name"];
$name = $_FILES["inputFile"]["name"];
move_uploaded_file($tmp_name, "$destination/$name");
?>
But it doesn't work. I'm not an expert of POST method, so i don't know what I'm doing wrong. Can you help me?
The problem is because your append values... I Checked in my local with your Script and alter something like ajax-url and success message for my convenient This is my code Please Check and let me know:
$("#Invia").click(function (){
var form = new FormData();
var myFormData = document.getElementById('inputFile').files[0]; //get the file
if (myFormData) { //Check the file is emty or not
form.append('inputFile', myFormData); //append files
}
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: form,
url: "test1.php", //My reference URL
dataType : 'json',
success: function(jsonData){
if(jsonData == 1)
$('#img_msg').html("Image Uploaded Successfully");
else
$('#img_msg').html("Error While Image Uploading");
}
});
});
You don't need to change your php file but, Double check your Folder path is correct for storing the Image...

PHP ajax uploading images

I'm trying to do a file upload through ajax and php. The PHP works fine when called directly, but each time I call it through ajax it is failing. I'm not getting any errors (annoying) it just does not want to upload.
My JQUERY looks like
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
form_data.file = file_data;
console.log(form_data);
var fileType = $(this).parent().find('input[type="hidden"]').val()
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
fileType:fileType,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
and my PHP looks like
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
print_r($_FILES[file_up]);
if ($_FILES[file_up][size]>250000){$msg=$msg."Your uploaded file size is more than 250KB
so please reduce the file size and then upload.<BR>";
$file_upload="false";}
$file_name=$_FILES[file_up][name];
$add="medicalPaperwork/$file_name"; // the path with the file name where the file will be stored
if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
echo "Thank god!";
}else{echo "Fuck you.";}
}else{
echo $msg;
}
What am I doing wrong? I'm going crazy trying to figure this out.
edit: the content of the form_data
You are using FormData incorrectly, use append to set the fields you want to upload
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
var fileType = $(this).parent().find('input[type="hidden"]').val()
form_data.append('file_up', file_data);
form_data.append('fileType', fileType);
console.log(form_data);
console.log(fileType);
$.ajax({
url: '/docs/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: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});

codeigniter file upload using AJAX

hello i have this function using AJAX. i need to retrieve the file's name size type and i will have to save it to my database..
here is my code.
function UploadImage() {
var data = new FormData($('#fileName'));
Jquery.each($('#fileName')[0].files, function(i,file) {
data.append(i,file);
}
$.ajax({
type: 'post',
data: data,
url: 'controller/function',
cache: false,
ContentType: false,
ProcessData: false,
success: function(data) {
alert(data);
}
}
when i will retrieve the data coming from the ajax request through my controller, i cant get the data of the files using _$Files[] it has error saying undefined index.
This may work for you
function UploadImage()
{
var data = new FormData(document.getElementById("fileName"));//remember fileName is your form id.
//You dont need this
/*Jquery.each($('#fileName')[0].files, function(i,file) {
data.append(i,file);
}*/
//you don't need to modify the data. data already contains whole form information.
$.ajax({
type: 'post',
data: data,
url: 'controller/function',//better use full path instead of relative path
cache: false,
ContentType: false,
ProcessData: false,
success: function(data) {
alert(data);
}
}

ajax send file and variable to php

I'm using an ajax call to upload a file, handled by PHP. The file should be placed in a specific directory based on a jquery variable. I can get the file to upload, but cannot pass the variable along with the file. PHP reports an undefined index error.
Ajax code:
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
I tried changing the data property to "fd+'&myVar='+myVar, however PHP cannot parse the data correctly and returns undefined index error for both the $_FILES['file'] variable as well as the $_POST['myVar'] variable.
How can I send both the file and a variable?
If you need another form field, call fd.append a second time:
fd.append('file', document.getElementById('select').files[0]);
fd.append('myVar',myVar);
You can append values other than files to a formdata object.
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
fd.append( 'myVar', myVar);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
Refer to $.ajax jQuery API Documentation.
It is clearly stated that data should be an object with key-value pairs representing data accepted by server-side script. Whatever, not sure why jQuery seems to not accept your data. Maybe you should try this out manually.
Since your test.php accepts POST data as myVar your jQuery Ajax configuration should probably look like
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myVar: document.getElementById('select').files[0]
},
success: function(e){
// some code here
}
});

PHP not receiving formData object from ajax

I'm testing out sending a formData object to PHP (I am following http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/), but am having some difficulty getting it off the ground. First, the formData object is created and populated with:
var formdata = new FormData();
formdata.append('my_key','my_value');
Then my ajax call with jQuery is:
$.ajax({
url: 'php_upload.php',
type: 'POST',
cache: false,
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
}
});
With the php_upload.php file containing:
<?php
echo $_FILES['my_key']['name'];
?>
But I get an undefined index: my_key error in the console.
Anyone have any idea what I might be doing wrong? Been scratching my head for ages.
You haven't added any files to the FormData, just a string which can be accessed by $_POST['my_key'].
To pass a file the second parameter of FormData.append has to be a FILE or a BLOB.

Categories