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
}
});
});
Related
I have an Excel file which I upload using JavaScript. Once it is uploaded I perform some operations on it. Then I create a new Excel file from that data which is further downloaded.
Now everything is working fine, but the ajax response is returning a binary result of the output file. I want to download this file. The result of console.log is:
PK=�N%���a[Content_Types].xml͔]K�0���%��f� "�v��R���kX�����m��+����4�<�'��2�jgs6�,+��v����Sz���*a�����tr5^�=`Bb�9+c����,��9��.T"�kXr/�J,���[.��`ck6�?h�\��,*���ܠ}3�c�C+��9�-E��|c�j�BKPN�+�d��u��O1�
`o�Ba +���G�
�61yܑ{�y���ef�l�`�}���N�6=� �,�-m��ҷ.�ޝ[]��z�*�mע�x�GN���nN�J=YB��k�;��8~�����C�M5țax��?���1�'9n�(�"�z����o�������'PK=�N�78�K_rels/.rels���j�0��{
�{���1F�^ʠ�2��l�$���-}�y����Î��O��v�y�;�؋Ӱ.JP��^�����Yű�3G�Ww�g)���>�qQC��D���b!�]�i$L��3����2n���oT�:Z
�h����[��4�ი��]��yN�,ە�>�>�j
-'
V�)�#��EF^6��n���8q"K��H��>_ׄ����eƏ�<⇄�Ud�v��
T�PK=�Nx����xl/_rels/workbook.xml.rels���j�0��}
��X�ӆR"�R
���im�ؒ��?~��
m����;�1B���гw�sV#����*�;�
x��V��"I�e�,
1®��>c/)�D��Ȓ����<*�����h�M�� )��r/�A���<��0���̓������
$('#subb').on('click', function() {
var file_data = $('#excel_upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'processing.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){
var a = document.createElement('a');
var url = data;
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);
}
});
});
So any idea how to convert the binary file into excel and further download it
EDIT 1:
So i solved it. Below is the javascript code i wrote
$('#submit_btn').on('click', function() {
var file_data = $('#excel_upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'process.php', // point to server-side PHP script
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
beforeSend: function() {
$("#submit_btn").html('<img src="https://thumbs.gfycat.com/UnitedSmartBinturong-max-1mb.gif" style="height:20px">');
},
success: function(data){
var a = $("<a>");
a.attr("href",data.file);
$("body").append(a);
a.attr("download","file.xls");
a[0].click();
a.remove();
$("#submit_btn").html('Submit');
}
});
});
And at the server end
$writer->save('php://output');
$xlsData = ob_get_contents();
ob_end_clean();
$response=array('file'=>"data:application/vnd.msexcel;base64,"base64_encode($xlsData));
die(json_encode($response));
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.
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...
I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});
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
}
});