I new to this site as well as to ajax, before posting here, although I searched for, nut not get proper answer to my question.
I have form through which I can upload and than save file, all this happening through ajax.
$('#'+loader).fadeIn('fast');
var input = document.getElementById(fileid);
file = input.files[0];
var filename= $('#'+fileid).val();
var exts = ["pdf", "doc", "docx", "PDF", "DOC", "DOCX"];
if(file != undefined){
formData= new FormData();
if ( filename )
{
// split file name at dot
var get_ext = filename.split('.');
// reverse name to check extension
get_ext = get_ext.reverse();
// check file type is valid as given in 'exts' array
if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){ var found = true; } else { var found = false; }
}
if(found) {
formData.append("image", file);
$.ajax({
url: uri,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
if(data.length!=0)
{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+successid).fadeIn('fast');
$('#'+inputhidden).val(data);
$('#'+imgname).fadeIn('fast');
$('#'+filesavebtn).fadeIn('fast');
$('#'+imgname).html(data);
}else if(data.length==0)
{
$('#'+loader).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+errorid).fadeIn('fast');
}
}
});
}
else{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+exerror).fadeIn('fast');
}
}else{
}
and getting saved through
var fileval= $('#'+fileid).val();
var fileuniqval= $('#'+fileuniqid).val();
$.ajax({
url: pageurl,
type: 'POST',
data: 'fileupload='+fileval+'&identi='+fileuniqval+'&uniqids=fileuploading',
success: function(data)
{
if(data=='FALSE'){
alert("Server Error, please try again.");
}if(data=='TRUE'){
$('#'+hide1).fadeOut('fast');$('#'+hide2).fadeOut('fast');$('#'+hide3).fadeOut('fast');
$('#'+inputid).val('');
$('#'+successmsg).fadeIn('fast');
$('#'+filearea).css({ 'border-color': '#008000', 'border-width':'2px', 'border-style':'solid' });
$('#'+filearea).animate({ 'backgroundColor': '#008000', 'color': '#fff'}, 1000);
$('#'+filearea).animate({ 'backgroundColor': '#fff', 'color': '#000'}, 3000);
}
}
});
Now my question is that I want to get this upload and save procedure in one go! Although I tried my to merge both function by nesting one in other but not working as per expectations.
$('#'+loader).fadeIn('fast');
var input = document.getElementById(fileid);
file = input.files[0];
var filename= $('#'+fileid).val();
var exts = ["pdf", "doc", "docx", "PDF", "DOC", "DOCX"];
var fileval= $('#'+inputhidden).val();
var fileuniqval= $('#'+fileuniqid).val();
if(file != undefined){
formData= new FormData();
if ( filename )
{
// split file name at dot
var get_ext = filename.split('.');
// reverse name to check extension
get_ext = get_ext.reverse();
// check file type is valid as given in 'exts' array
if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){ var found = true; } else { var found = false; }
}
if(found) {
formData.append("image", file);
$.ajax({
url: uri,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
if(data.length!=0)
{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+successid).fadeIn('fast');
$('#'+inputhidden).val(data);
$('#'+imgname).fadeIn('fast');
//$('#'+filesavebtn).fadeIn('fast');
$('#'+imgname).html(data);
$.ajax({
url: pageurl,
type: 'POST',
data: 'fileupload='+fileval+'&identi='+fileuniqval+'&uniqids=fileuploading',
success: function(data)
{
if(data=='FALSE'){
alert("Server Error, please try again.");
}if(data=='TRUE'){
$('#'+successid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+errorid).fadeOut('fast');
$('#'+fileid).val('');
$('#'+hide1).fadeIn('fast');
$('#'+filearea).css({ 'border-color': '#008000', 'border-width':'2px', 'border-style':'solid' });
$('#'+filearea).animate({ 'backgroundColor': '#008000', 'color': '#fff'}, 1000);
$('#'+filearea).animate({ 'backgroundColor': '#fff', 'color': '#000'}, 3000);
}
}
});
}else if(data.length==0)
{
$('#'+loader).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+errorid).fadeIn('fast');
}
}
});
}
else{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+exerror).fadeIn('fast');
}
}else{
}
Related
I need your help to upload an image on my server.
Indeed, with this code, I have an array(0) {} response while the values are well populated.
No image is uploaded... thank you for your help, here are my two files:
index.php
<input type="file" id="txt_image_user" name="txt_image_user" accept="image/*" required >
<script>
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: {fd:fd, handle:handle, reference:reference},
contentType: false,
processData: false,
error: function (e) {console.log('Ajax Error', e);alert('Erreur Ajax');},
success: function(response){
console.log(response);
},
});
}
</script>
_upload-image.php
<?php require($_SERVER['DOCUMENT_ROOT']."/ew-includes/config.php");
var_dump($_POST);
$PathImage = $_SERVER['DOCUMENT_ROOT']."/ew-content/images/images-clients/";
if (!is_dir($PathImage)) {mkdir($PathImage);}
if(isset($_POST["handle"])) {
if(is_array($_POST["handle"])) {$handle = implode(", ", $_POST['handle']);} else {$handle = $_POST['handle'];}
if(is_array($_POST["reference"])) {$reference = implode(", ", $_POST['reference']);} else {$reference = $_POST['reference'];}
$img_name = $_FILES["txt_image_user"]["name"];
$img_tmp = $_FILES["txt_image_user"]["tmp_name"];
$filename = "ew".$reference."_".$handle."_".date("YmdHi");
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
$photo = $filename.".".$ext;
$resultat = move_uploaded_file($img_tmp, $PathImage.$photo);
echo "img_name: ".$img_name."\n";
echo "img_tmp: ".$img_tmp."\n";
echo "ext: ".$ext."\n";
echo "photo: ".$photo."\n";
echo "resultat: ".$resultat."\n";
}
Thanks for your help.
I specify that I am new in Jquery
That's not the way to use FormData it should be the data. You can append other values to it.
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
fd.append('handle', handle);
fd.append('reference', reference);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: fd,
contentType: false,
processData: false,
error: function(e) {
console.log('Ajax Error', e);
alert('Erreur Ajax');
},
success: function(response) {
console.log(response);
},
});
}
I'm trying to save the generated PDF file with JSPDF plugin into the server instead of being saved on the client side, the javascript part that handles the JsPDF is this:
<script type="text/javascript">
(function(){
var
form = $('.form'),
cache_width = form.width(),
//cache_height = form.height(),
a4 =[ 595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click',function(){
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF(){
getCanvas().then(function(canvas){
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit:'px',
format:'a4'
});
var imgWidth = 220;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
processData: false,
contentType: false,
success: function(response){
alert(response);
console.log(response)
},
error: function(err){
alert(err);
console.log(err)
}
});
});
}
// create canvas object
function getCanvas(){
form.width((a4[0]*1.33333) -80).css('max-width','none');
return html2canvas(form,{
imageTimeout:2000,
removeContainer:true
});
}
}());
</script>
the upload.php file should move the generated pdf file or its content to the Uploads folder but it seems that the $_FILES['data'] is empty
<?php
if(!empty($_FILES['data'])) {
// PDF is located at $_FILES['data']['tmp_name']
$content = file_get_contents($_FILES['data']['tmp_name']);
//echo $content;
$location = "uploads/";
move_uploaded_file($_FILES['data']['tmp_name'], $location.'random-name.pdf');
} else {
throw new Exception("no data");
}
the response I get back from Ajax is "Notice: Undefined index: data ".
Thanks in advance for any help.
I finally got it to work using this code:
var pdf = btoa(doc.output());
var file_name = $('#id').val();
//var file_name = 'hello world';
$.ajax({
method: "POST",
url: "upload.php",
data: {data: pdf, filename: file_name},
}).done(function(data){
// alert(data);
console.log(data);
});
and on the server side upload.php like this:
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
$fileName = $_POST['filename'];
file_put_contents( "uploads/".$fileName.".pdf", $data );
} else {
echo "No Data Sent";
}
exit();
I have this function to get values from a form
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
var batchid = $("input[name='batchid']").val();
var yrstart = $("input[name='yrstart']").val();
var yrend = $("input[name='yrend']").val();
$.ajax({
url:"fetch_import.php",
method:"POST",
data: { batchid : batchid, yrstart: yrstart, yrend: yrend, fd},
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
and a php code like this:
enter code here$bcid = $_POST['batchid'];
$yrs = $_POST['yrstart'];
$yrg = $_POST['yrend'];
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$FileType = pathinfo($location,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$location);
passing the file doesn't work. I've searched for this but still not working for me, i think i'll understand how it will work. Any idea? Tyia
You should append your fields to fd and simply use that as data-parameter in $.ajax:
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
fd.append('batchid', $("input[name='batchid']").val());
fd.append('yrstart', $("input[name='yrstart']").val());
fd.append('yrend', $("input[name='yrend']").val());
$.ajax({
url:"fetch_import.php",
method:"POST",
data: fd,
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.
function save()
{
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append('files',files[i],files[i].name);
}
var datastring = $("#businessform").serializeArray();
$.each(datastring,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
Here's the PHP
$success = 0;
$logo = "";
$logo_error = 0;
$sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
$fields = array(
':bname'=>$_POST['businessname'],
':phone'=>$_POST['businessphone'],
':email'=>$_POST['businessemail'],
':id'=>$_POST['vendorid']
);
$q=$con->update_query($sql,$fields);
if($q)
{
//save logo
$businessid = $con->lastID;
if(!empty($_FILES['files']['tmp_name']))
{
$ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
{
$logo = "logo".$businessid;
move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
}
else
{
$logo_error = 1;
}
}
$success = 1;
}
echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));
The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.
Thank you so much.
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);
function save()
{
var datastring = FormData($("#businessform")[0]);
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
I am upload a file in php codeigniter project using a ajax. The file is uploading succesfully. But I also want to post some extra values to database with this. I am not sure how to do it. Can anybody please tell me how to pass another data fields while saving a file in php
Here is my js code
$("#btnupdatecover").click(function(event){
alert(coverPostion);
if($("#fileuploadcover").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
clearAll();
}
});
//
event.preventDefault();
}
}
else
{
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
}
});
My PHP Code
public function updatedp()
{
$var = $_FILES ['fileUp'];
$img=$_FILES ['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
}
else
{
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
I just pass extra fields with this to post in database.
Thanks
You can achieve this:
Approach 1
Use hidden fields into the form.
Approach 2
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: {formData: formData, var1: 'value', var2: 'value'},
dataType: 'json',
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
clearAll();
}
});
Now these value you will get your controller.