Submit a form with Javascript and handle it with ajaxForm - javascript

I am currently changing my system in order to have a loading progress bar when I now submit my form.
In my old system, I had this form and this script to check if the file exists and is in the right format:
Index.php
<form method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">
<input type="file" name="imageSent" id="imgFile" class="inputImg" />
<label for="imgFile" class="labelForImgF">
<span>Select Img</span>
</label>
<button type="button" class="btnSubmit" onclick='verifyImg();'>
<span>Send</span>
</button>
</form>
<script>
function verifyImg() {
document.getElementById("warning").innerHTML = "";
var fileName = document.getElementById("imgFile");
if(fileName.files.item(0) == null) {
document.getElementById("warning").innerHTML = "You must select an img";
} else {
if(!isValidFileType(fileName.files.item(0).name,'image')) {
document.getElementById("warning").innerHTML = "Bad format";
} else {
document.getElementById('myForm').submit();
document.getElementById("warning").innerHTML = "Sucess";
}
}
}
var extensionLists = {};
extensionLists.image = ['jpg', 'nef', 'bmp', 'png', 'jpeg', 'svg', 'webp', '3fr', 'arw', 'crw', 'cr2', 'cr3', 'dng', 'kdc', 'mrw', 'nrw', 'orf', 'ptx', 'pef', 'raf', 'R3D', 'rw2', 'srw', 'x3f'];
function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.toLowerCase().split('.').pop()) > -1;
}
</script>
And here is my new system, It works well with ajax but I can't check if the format is correct because as long as I put the onclick:verifyImg(); in my button the form submits without passing by the Ajax system.
Here is my new code:
<form method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">
<input type="file" name="imageSent" id="imgFile" class="inputImg" />
<label for="imgFile" class="labelForImgF">
<span>Select Img</span>
</label>
<button class="btnSubmit">
<span>Send</span>
</button>
</form>
<div id="bararea">
<div id="bar"></div>
</div>
<div id="percent"></div>
<div id="status"></div>
<script>
$(function() {
$(document).ready(function(){
var bar = $('#bar')
var percent = $('#percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
percent.html(percentVal);
bar.width(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
});
</script>
These two systems work well separately, but I can't mix them, in order to validate my form with javascript and submit it with Ajax.
I think I'm not understanding well how Ajax works, can you help me?
I am a beginner please be indulgent.
Solution:
I tried Chris G answer and changed the function beforeSend by beforeSubmit and now It works perfectly.
Code:
<form method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">
<input type="file" name="imageSent" id="imgFile" class="inputImg" />
<label for="imgFile" class="labelForImgF">
<span>Select Img</span>
</label>
<button class="btnSubmit">
<span>Send</span>
</button>
</form>
<div id="bararea">
<div id="bar"></div>
</div>
<div id="percent"></div>
<div id="status"></div>
<script>
function verifyImg() {
document.getElementById("warning").innerHTML = "";
var fileName = document.getElementById("imgFile");
if(fileName.files.item(0) == null) {
document.getElementById("warning").innerHTML = "You must select an img";
return false;
} else {
if(!isValidFileType(fileName.files.item(0).name,'image')) {
document.getElementById("warning").innerHTML = "Bad format";
return false;
} else {
return true;
document.getElementById("warning").innerHTML = "Sucess";
}
}
}
var extensionLists = {};
extensionLists.image = ['jpg', 'nef', 'bmp', 'png', 'jpeg', 'svg', 'webp', '3fr', 'arw', 'crw', 'cr2', 'cr3', 'dng', 'kdc', 'mrw', 'nrw', 'orf', 'ptx', 'pef', 'raf', 'R3D', 'rw2', 'srw', 'x3f'];
function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.toLowerCase().split('.').pop()) > -1;
}
</script>
<script>
$(document).ready(function(){
var bar = $('#bar')
var percent = $('#percent');
var status = $('#status');
$('form').ajaxForm({
beforeSubmit: function() {
if (!verifyImg()) return false ;
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
percent.html(percentVal);
bar.width(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
</script>

use this code, I've check it, it runs well. If you want to test the upload progress, In google browser's console, select network→then select slow 3G here:
otherwise, you can't see the upload progress increase, you will see 100% in a flash unless you photo has a extremely big size.
user can't select non image file by adding accept attribute to the input box accept="image/*", even if not using this attribute, the javascript will validate the file format by there code, you can add other types here if you need "(jpeg|png|bmp)":
var file = $('input[name="photo"]').get(0).files[0];
var matchArr = file.type.match(/image\/(jpeg|png|bmp)/);
if (!matchArr) {
alert("file type not allow!");
return false;
}
This is the full code:
$(document).ready(function() {
$('input[type="button"]').on('click', function() {
var file = $('input[name="photo"]').get(0).files[0];
var matchArr = file.type.match(/image\/(jpeg|png|bmp)/);
if (!matchArr) {
alert("file type not allow!");
return false;
}
var words = $('input[name="words"]').val();
var formData = new FormData();
formData.append('photo', file);
formData.append('words', words);
$.ajax({
type: 'post',
url: '',
data: formData,
//contentType must be false(otherwise it will use default value:application/x-www-form-urlencoded; charset=UTF-8, which is wrong)
contentType: false,
//tell jquery don't process data(otherwise it will throw an error:Uncaught TypeError: Illegal invocation)
processData: false,
xhr: function() {
let xhr = new XMLHttpRequest();
//listening upload progress
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
let progress = e.loaded / e.total;
progress = Math.round(progress * 10000) / 100 + '%';
$('.upload-progress').html(progress);
}
}, false);
return xhr;
},
success: function(response) {
console.log(response);
}
});
return false;
});
});
<html>
<head>
<title>AjaxFormDataUpload</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
#upload-form {
width: 50%;
margin: 0 auto;
border: 1px solid blue;
}
.field {
padding: 10px;
}
.submit-btn {
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<form id="upload-form">
<div class="field">
<input type="file" name="photo" accept="image/*">
<span class="upload-progress"></span>
</div>
<div class="field">
<input type="text" name="words">
</div>
<div class="submit-btn">
<input type="button" value="submit">
</div>
</form>
</body>
</html>

Related

Dropzone display server images but not saving laravel

I'm using Dropzone.js,I displayed server images inside dropzone box with remove link and it works fine but my problem is when I click on butto to save uploaded images server images not saving in database just new uploaded images are saving
my code
<script type="text/javascript">
Dropzone.options.dropzone =
{
autoProcessQueue: false,
maxFiles: 50,
maxFilesize: 12,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
uploadMultiple: true,
timeout: 50000,
init: function () {
var myDropzone = this;
$.get('/getphoto',{'key': $('[name=key]').val()},function(data){
var files = data;
console.log(files.length);
for (var i = 0; i < files.length; i++) {
var name= files[i].name;
var link = "http://127.0.0.1:8000/storage/images/events/galleries/"+ name;
console.log(link);
var mockFile = { name: files[i].name, size: 128456, type: 'image/png', url:link};
myDropzone.emit('addedfile', mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, link);
myDropzone.emit('complete', mockFile);
myDropzone.files.push(mockFile);
var existingFileCount = 1; // The number of files already uploaded
myDropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
});
// Update selector to match your button
$("#button").click(function (e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on('sending', function(file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $('#dropzone').serializeArray();
$.each(data, function(key, el) {
formData.append(el.name, el.value);
});
});
},
removedfile: function(file)
{
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : myDropzone.removeFile(file);
},
success: function(file, response)
{
var name = file.upload.filename;
console.log(name);
window.location.href = "{{ route('eventlist') }}";
},
error: function(file, response)
{
return false;
}
};
function del(file)
{
console.log(file.name);
return myDropzone.removeFile(file);
}
</script>
my view blade:
<div>
<form action="{{ route('savegallery',$event->id) }}" class="dropzone" id="dropzone" method="POST" class="dropzone" enctype="multipart/form-data">
#csrf
{{-- <div class="fallback">
<input name="images" type="file" multiple="multiple">
</div> --}}
<div class="dz-message needsclick">
<div class="mb-3">
<i class="display-4 text-muted mdi mdi-upload-network-outline"></i>
</div>
<h4>Drop files here or click to upload.</h4>
</div>
</form>
</div>
<div class="text-center mt-4">
<button type="submit" id="button" class="btn btn-primary waves-effect waves-light">Send
Files</button>
</div>
First I delete all images then I get images from dropzone then save it
public function savegallery(Request $request,$id){
$eventgalleries = Eventgallery::where('event_id',$id)->delete();
foreach ($request->file('file') as $img) {
// $image = new Eventgallery;
//get file name with extention
$filenameWithExt = $img->getClientOriginalName();
//get just file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//GET EXTENTION
$extention = $img->getClientOriginalExtension();
//file name to store
$fileNameToStore = $filename . '_' . time() . '.' . $extention;
//upload image
$path = $img->storeAs('public/images/events/galleries', $fileNameToStore);
$url = asset('storage/images/events/galleries/' . $fileNameToStore);
$img = new Eventgallery;
$img->name = $fileNameToStore;
$img->event_id = $id;
$img->save();
}
return redirect()->route('eventlist')->with('success', 'The galleries created successfully.');
}
and this function for route (/getphoto) to get all images and then display it in dropzone
public function getphoto(){
$data = Eventgallery::all()->toArray();
return $data;
}
Can someone help me I spend many days to find a solve but no result.

PHP - Uploading multiple files with Javascript and PHP

its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>
<body>
<script type="text/javascript">
function fileChange()
{
//FileList Objekt aus dem Input Element mit der ID "fileA"
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if(!file) {
return;
}
var x = substr(file.name, -4);
document.getElementById("status").innerHTML = x;
/*
if (x != ".pdf") {
document.getElementById("fileA").files = null;
file = null;
fileList = null;
alert("Wrong Data");
return;
} */
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile()
{
//Wieder unser File Objekt
for(i=0;i < document.getElementById("fileA").files; i++) {
var file = document.getElementById("fileA").files[i];
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
//Fügt dem formData Objekt unser File Objekt hinzu
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
}
}
function uploadAbort() {
if(client instanceof XMLHttpRequest)
//Briecht die aktuelle Übertragung ab
client.abort();
}
</script>
<form action="" method="post" enctype="multipart/form-data">
<input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
<input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
<input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
<div id="status"></div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>
</div>
</body>
</html>
So this is my HTML Code and following up my upload.php:
<?php
if (isset($_FILES['datei']))
{
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>
My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.
There are some tutorials in the internet, that you can simply find by googling "multiple file upload". Anyway here is one of the examples:
The HTML
<!-- IMPORTANT: FORM's enctype must be "multipart/form-data" -->
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
Listing Multiple Files with JavaScript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
The input.files property provides an array of files for which you can check the length; if there's a length, you can loop through each file and access the file paths and names.
Receiving and Handling Files with PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
PHP creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.
Source
Demo
This is uploading using ajax. There are other ways such the use of iframe and jquery's $.load().
ajax_upload.js
Hmm... FormData is not IE-safe. So, you may want to resort to iframe & $.load().
function doUpload(fle_id, url_upld)
{
var upldLimit = 2000000; // 2mb by default;
if( $('#'+fle_id)[0] == undefined || $('#'+fle_id)[0].files.length == 0 ) {
alert('nothing to upload');
return;
}
// put files to formData
var tfSize = 0; // in bytes
var fd = new FormData();
$.each($('#'+fle_id)[0].files, function(i, file) {
fd.append(i, file);
tfSize = tfSize + file.size;
});
// you may check file size before sending data
if(tfSize > upldLimit) {
alert('File upload exceeded the '+(upldLimit/1000000)+' MB limit.');
return;
}
// actual data transfer
$.ajax({
url: url_upld,
cache: false,
data: fd,
type: 'POST',
contentType : false,
processData : false,
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
}
upload_form.html
Let's use jquery to make things simple.
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax_upload.js"></script>
<script type="text/javascript">
$(function(){
$('form').submit(function(e){
if( e.preventDefault ) e.preventDefault(); // chrome/firefox
else e.cancelBubble(); // IE
// supply file input id and upload url
doUpload( 'fle', $(this).attr('action') );
});
});
</script>
Upload
<form action="ajax_upload.php"
method="post"
enctype="multipart/form-data"
accept-charset="utf-8"
>
<input type="file" id="fle" name="fle[]" multiple >
<button type="submit">Upload</button>
</form>
ajax_upload.php
<?php
if(count($_FILES) == 0) {
echo 'Nothing uploaded.';
exit;
}
$upldPath = 'E:/stack/upload/';
foreach($_FILES as $file) {
if ($file['error'] == UPLOAD_ERR_OK) {
try {
if( !move_uploaded_file( $file["tmp_name"], $upldPath . $file['name']) ) {
// abort even if one file cannot be moved.
echo 'Cannot upload one of the files.';
exit;
}
}
catch(Exception $e) {
echo 'Cannot upload the files.';
exit;
}
} else {
// abort even if one file has error.
echo 'Cannot upload one of the files.';
exit;
}
}
echo 'Upload successful!';
?>
Here is a simple approach to solving this issue.
This FormData append method works on IE 10 up and any other browser.
let files = []
let formData = new FormData
let filesInput = document.getElementById('files')
function prepareFiles() {
files = filesInput.files
}
function uploadFiles() {
// Arrange the files as form data to be sent to php
files = Array.from(files)
files.forEach(file => formData.append('files[]', file))
// See all selected files
console.log('Files')
console.log(formData.getAll('files[]'))
// Then send to php with jquery, axios e.t.c
console.log('Server response')
$.post('/pathtophpscript', formData, (response) => {
console.log(response)
}).catch(error => console.log(error))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploads" id="files" onchange="prepareFiles()" multiple>
<br/><br/>
<input type="submit" name="Upload" onclick="uploadFiles()">

CodeIgniter AJAX file upload, $_FILE is empty when upload

Iam writing a script that uploads files via Drag and Drop using jQuery which reads the file on drop and adds it to an array of files like so:
var files = [];
$(document).ready(function() {
jQuery.fn.dropbox = function(config) {
var dragging = 0;
var dragEnter = function(e) {
e.stopPropagation();
e.preventDefault();
dragging++;
$(".external-drop-indicator").fadeIn();
$(".toast.toast-success").fadeIn().css("display", "inline-block");;
return false;
};
var dragOver = function(e) {
e.stopPropagation();
e.preventDefault();
return false;
};
var dragLeave = function(e) {
e.stopPropagation();
e.preventDefault();
dragging--;
if(dragging === 0) {
$(".external-drop-indicator").fadeOut();
$(".toast.toast-success").fadeOut();
}
return false;
};
var drop = function(e) {
var dt = e.dataTransfer;
var files_upload = dt.files;
e.stopPropagation();
e.preventDefault();
if(files_upload && files_upload.length > 0 && config.onDrop !== undefined) {
files.push(files_upload);
config.onDrop(files_upload);
}
$(".external-drop-indicator").fadeOut();
$(".toast.toast-success").fadeOut();
};
var applyDropbox = function(dropbox) {
dropbox.addEventListener('dragenter', dragEnter, false);
dropbox.addEventListener('dragover', dragOver, false);
dropbox.addEventListener('dragleave', dragLeave, false);
dropbox.addEventListener('drop', drop, false);
};
return this.each(function() {
applyDropbox(this);
});
};
});
In summary what it does is, adds an extended jQuery function to enable drag and drop on a certain element of the website in which the function is applied.
Then I apply the extended functionality to the body for it to enable the file Drag and Drop functionality like so:
$(document).ready(function() {
$('body').dropbox({
onDrop: function(f) {
$(f).each(function(idx, data) {
var file_name = data.name;
var extension = file_name.split('.');
file_name = extension[0];
extension = extension[1];
if(extension == 'pdf' || extension == 'xls') {
showAjaxModal(base_url + 'index.php?modal/popup/file_create/' + folder_id + '/' + extension + '/' + file_name);
} else {
$(".upload-area").append('<div class="alert alert-danger" style="display:inline-block;width:480px;"><strong>Error!</strong> File type is incorrect.</div>');
}
});
}
});
});
In summary what this does is adds the Drag and Drop functionality to the body and when a file is dropped it detects the extension of the file by splitting the name and the extension, so that I can verify that the extension of the file that was dropped is correct. Then it proceeds to show a modal to fill information about the file that is being uploaded for later submission, if the file extension is correct.
Then I proceed to fill the file information using CodeIgniter's function "form_open()" when the modal pops like so:
<?php echo form_open(base_url() . 'index.php?client/file/create/' . $param2, array('class' => 'form-horizontal form-groups-bordered validate ajax-upload', 'enctype' => 'multipart/form-data')); ?>
<div class="col-md-4 file-info">
<div class="icon-<?=($param3 == 'pdf' ? 'pdf' : 'document')?>"></div>
<p>
<?php echo $param4;?>
</p>
</div>
<div class="col-md-8 new-file">
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<input type="text" class="form-control" name="tags" data-validate="required" data-message-required="Field is required" placeholder="File tags" value="" autofocus>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<input type="text" class="form-control" name="name" data-validate="required" data-message-required="Field is required" placeholder="File name" value="" autofocus>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<textarea rows="5" class="form-control" name="description" data-validate="required" data-message-required="Field is required" placeholder="File description" value="" autofocus></textarea>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-7">
<button type="submit" class="btn btn-info" id="submit-button">Upload</button>
<span id="preloader-form"></span>
</div>
</div>
<?php echo form_close(); ?>
This basically creates a form which later will be submitted via Ajax.
Now I proceed to handle the file submission via jQuery for the information to be sent with the file or files that are being uploaded like so:
$(document).ready(function(e) {
$('.ajax-upload').submit(function(e) {
e.preventDefault();
var $elm = $(this);
var fd = new FormData();
for(var i = 0; i < files.length; i++) {
fd.append("file_" + i, files[i]);
}
var form_data = $(".ajax-upload").serializeArray();
$.each(form_data, function(key, input) {
fd.append(input.name, input.value);
});
var opts = {
url: $elm.attr('action'),
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: uValidate,
success: showResponse
};
if(fd.fake) {
opts.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
xhr.send = xhr.sendAsBinary;
return xhr;
}
opts.contentType = "multipart/form-data; boundary=" + fd.boundary;
opts.data = fd.toString();
}
jQuery.ajax(opts);
return false;
});
});
Basically the form default action is overwritten and the files that were submitted on the previous code chunk for the drag and drop functionality are now appended to formData which later gets joined by the form data that was on the form I submit. Then the formData is sent via an AJAX call.
Now the controller looks like this, it handles the AJAX call and then executes the File Upload method on the model like so:
function file($param1 = '', $param2 = '', $param3 = 0) {
if ($this->session->userdata('client_login') != 1) {
$this->session->set_userdata('last_page', current_url());
redirect(base_url(), 'refresh');
}
if ($param1 == 'create')
$this->crud_model->create_file($param2);
if ($param1 == 'edit')
$this->crud_model->update_file($param2);
if ($param1 == 'delete')
$this->crud_model->delete_file($param2, $param3);
$page_data['page_name'] = 'files';
$page_data['page_title'] = 'Files List';
$page_data['folder_id'] = $param3;
$this->load->view('backend/index', $page_data);
}
Here is the model method:
function create_file($folder_id) {
$data['name'] = $this->input->post('name');
$data['tags'] = $this->input->post('tags');
$data['description'] = $this->input->post('description');
$data['type'] = 'file';
$data['folder_id'] = $folder_id;
$data['client_id'] = $this->session->userdata('login_user_id');
$config['upload_path'] = 'uploads/tmp/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$this->load->library('upload');
$this->upload->initialize($config);
var_dump($_FILES);
die();
foreach($_FILES as $field => $file)
{
//var_dump($_FILES); die();
// No problems with the file
if($file['error'] == 0)
{
// So lets upload
if ($this->upload->do_upload($field))
{
$data = $this->upload->data();
echo $data['full_path'];
}
else
{
$errors = $this->upload->display_errors();
var_dump($errors);
}
}
}
$this->db->insert('client_files' , $data);
}
So basically what happens is that the $_FILES array is empty, and the file doesn't get uploaded.
The "Request Payload" as viewed on Chrome's Developer Tools looks like this:
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="file_0"
[object FileList]
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="tags"
bsd
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="name"
asd
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="description"
asd
And the response I get from the var_dump() on the model is the following:
array(0) {
}
I have tried the solution on this question: Sending multipart/formdata with jQuery.ajax But no luck so far.
Any idea on what am I doing wrong and how to fix this issue? Thanks.
The problem here is that I'm sending the array of files instead of the single files on the AJAX call, specifically in this part of the code:
for(var i = 0; i < files.length; i++) {
fd.append("file_" + i, files[i]);
}
The solution was to append file by file to the formData instead of the array of files, something like this:
for(var i = 0; i < files[0].length; i++) {
fd.append("file_" + i, files[i]);
}
This will append every single file of the files array instead of the array of files itself and it solves the problem.
In conclusion I was sending the array of files instead of the single files, the clue to this was the [object FileList] that the request was showing instead of the files information, which now makes a request like this:
Content-Disposition: form-data; name="file"; filename="exfile.pdf"
Content-Type: application/pdf

SpreadJS ClipboardPasteOptions is set to "All" but no formatting is applied

i open a spreadsheet and i can see in console:
_clipBoardOptions: "All"
in activeSheet obj.
but whenever i try to paste formatting from excel it just passes the value.
any thoughts on were i'm going wrong.?
Basically the default is "All" but no formatting is passed to SpreadJS
Here's my initialisation
$("#ss").wijspread({sheetCount:1}); // create wijspread control
var spread = $("#ss").wijspread("spread"); // get instance of wijspread control
var sheet = spread.getActiveSheet();
also when i try manually adding the method after the initialisation as so :
sheet.clipBoardOptions($.wijmo.wijspread.ClipboardPasteOptions[0])
i tried looking for a solution but not much information is giving and the api is kinda bum !
thanks in advance to any of you helpers!
SpreadJS does not support pasting formatting from Excel. We are looking into ways that we can implement support for that in a future release.
For now, SpreadJS can only import the entire Excel workbook using the ExcelIO web service.
To get the content of a cell range copied to SpreadJS, the best suggestion I have now is to use ExcelIO to import that workbook to a hidden SpreadJS instance, then use ClipboardPasteUndoAction to copy and paste the range from the hidden SpreadJS to the visible one.
Here is a code example showing how to use the ExcelIO web service to import an Excel file:
<!DOCTYPE html>
<html>
<head>
<title>Excel IO Sample</title>
<link type="text/css" href="./css/cobalt/jquery-wijmo.css" rel="stylesheet" />
<link type="text/css" href="./css/gcspread.sheets.8.40.20151.0.css" rel="stylesheet" />
<script type="text/javascript" src="./external/jquery-1.9.1.js"></script>
<script type="text/javascript" src="./scripts/gcspread.sheets.all.8.40.20151.0.min.js"></script>
<script type="text/javascript">
$(function () {
//Initialize SpreadJS
new GcSpread.Sheets.Spread($("#ss").get(0), {sheetCount: 2});
//For Excel Import
$("#btn_Import").click(function () {
// SpreadJS Excel IO import service api.
var serverUrl = $("#serviceHost").val() + "/xsapi/import";
// Generate import api options
var formData = new FormData();
//Choose a file to import
var $importingFile = $("#loadExcel");
var theFile = $importingFile[0].files[0];
var accept = "application/json";
formData.append("file", theFile);
formData.append("ExcelOpenFlags", "NoFlagsSet");
formData.append("TextFileOpenFlags", "None");
formData.append("Password", "");
$.ajax({
//Server script to process data
url: serverUrl,
type: 'POST',
//Ajax events
success: function completeHandler(data, textStatus, jqXHR) {
var spread = $("#ss").data("spread");
spread.fromJSON(JSON.parse(jqXHR.responseText).spread);
},
error: function errorHandler(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
//Options to tell server return data with specified type
headers: {
"Accept": accept
}
});
});
//For Excel Export with Form Post.
$("#btn_Export").click(function () {
var spread = $("#ss").data("spread");
// SpreadJS Excel IO import service api.
var serverUrl = $("#serviceHost").val() + "/xsapi/export";
// Generate import api options
var optContentType = "application/json";
// Post the json from spreadjs.
var dataObj = {
"spread": spread.toJSON(),
"exportFileType": "xlsx",
"excel": {
"saveFlags": "NoFlagsSet",
"password": ""
},
};
var content = JSON.stringify(dataObj);
var formInnerHtml = '<input type="hidden" name="type" value="' + htmlSpecialCharsEntityEncode(optContentType) + '" />';
formInnerHtml += '<input type="hidden" name="data" value="' + htmlSpecialCharsEntityEncode(content) + '" />';
var $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
$iframe.ready(function () {
var formDoc = getiframeDocument($iframe);
formDoc.write("<html><head></head><body><form method='Post' action='" + serverUrl + "'>" + formInnerHtml + "</form>dummy windows for postback</body></html>");
var $form = $(formDoc).find('form');
$form.submit();
});
});
});
//gets an iframes document in a cross browser compatible manner
function getiframeDocument($iframe) {
var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframeDoc.document) {
iframeDoc = iframeDoc.document;
}
return iframeDoc;
}
var htmlSpecialCharsRegEx = /[<>&\r\n"']/gm;
var htmlSpecialCharsPlaceHolders = {
'<': 'lt;',
'>': 'gt;',
'&': 'amp;',
'\r': "#13;",
'\n': "#10;",
'"': 'quot;',
"'": 'apos;' /*single quotes just to be safe*/
};
function htmlSpecialCharsEntityEncode(str) {
return str.replace(htmlSpecialCharsRegEx, function (match) {
return '&' + htmlSpecialCharsPlaceHolders[match];
});
}
</script>
</head>
<body>
<h2>SpreadJS Excel IO Sample</h2>
<div style="margin-bottom: 10px">
<label><b>Excel IO Service Host : </b></label>
<input id="serviceHost" value="http://localhost/ExcelIO" style="width: 500px" />
</div>
<div id="ss" style="width: 660px; height: 500px; border: 1px solid gray; float: left">
</div>
<div style="width: 30%; height: 500px; margin-left: 15px; float: left">
<fieldset style="margin-bottom: 15px; height: 45%">
<legend><b>Excel IO Import Options</b></legend>
<input type="file" id="loadExcel" accept=".xlsx, .xls, .csv, .txt" />
<input id="btn_Import" type="button" value="Import" />
</fieldset>
<fieldset style="margin-bottom: 15px; height: 45%">
<legend><b>Excel IO Export Options</b></legend>
<input id="btn_Export" type="button" value="Export" />
</fieldset>
</div>
</body>
</html>
link: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#exceliocode.html
Here is a code example showing how to use the ClipboardPasteUndoAction:
$(document).ready(function () {
//There are two buttons in html page with the id "cutPasteBtn" and "copyPasteBtn".
var spread = new GcSpread.Sheets.Spread($("#ss").get(0),{sheetCount:3});
var sheet = spread.getActiveSheet();
sheet.setValue(0, 0, 1, GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(1, 0, 2, GcSpread.Sheets.SheetArea.viewport);
sheet.setFormula(2, 0, "=A1+A2", GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(0, 1, 3, GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(1, 1, 4, GcSpread.Sheets.SheetArea.viewport);
sheet.setFormula(2, 1, "=B1+B2", GcSpread.Sheets.SheetArea.viewport);
var fromRange = new GcSpread.Sheets.Range(0, 0, 3, 2);
var toRanges = [new GcSpread.Sheets.Range(4, 0, 3, 2)];
$("#cutPasteBtn").click(function () {
//Cut Paste Action
var clipboardCutPasteAction = new GcSpread.Sheets.UndoRedo.ClipboardPasteUndoAction(sheet, sheet, sheet, { fromRange: fromRange, pastedRanges: toRanges, isCutting: true, clipboardText: "" }, GcSpread.Sheets.ClipboardPasteOptions.Values);
clipboardCutPasteAction.execute(sheet);
});
$("#copyPasteBtn").click(function () {
//Copy Paste Action
var clipboardCopyPasteAction = new GcSpread.Sheets.UndoRedo.ClipboardPasteUndoAction(sheet, sheet, sheet, { fromRange: fromRange, pastedRanges: toRanges, isCutting: false, clipboardText: "" }, GcSpread.Sheets.ClipboardPasteOptions.Values);
clipboardCopyPasteAction.execute(sheet);
});
});
link: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#sccopy.html
Regards,
GrapeCity Experts

Img not fading out jQuery

I'm having some trouble with this JS / Jquery script, it was working completely yesterday, but today, it just wont work properly.
The loading .gif fades in, but just wont fade out...
This is my HTML
...
<div class="banner">
<img src="img/selosiade.png"/><br />
<form>
<input id="username" class="login" type="text" name="username" autocapitalize="off" placeholder="Nome de Usuário"><br />
<input id="password" class="login" type="password" name"password" autocapitalize="off" placeholder="Senha"><br />
<input type="button" value="Login" onClick="login.db();">
<img id="loading" src="img/loading.gif" />
...
(All tags are properly closed)
This what is set to the #loading id.
#loading{
display:none;
z-index:999;
margin-top:5px;
margin-left:50px;
position:absolute;
}
And this is the login.db() script:
var login = {
db: function () {
$('#loading').fadeIn(800, function () {
if (($('#username').val().length === 0) && ($('#password').val().length === 0)) {
$('#user_pass_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
} else if ($('#username').val().length === 0) {
$('#user_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
} else if ($('#password').val().length === 0) {
$('#pass_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
}
var pass1 = $('#password').val();
var pass = CryptoJS.SHA1(pass1);
var user = $('#username').val();
var flag = false;
$.ajax({
url: "http://apt-ghaschel.webatu.com/php/check.php",
type: "POST",
async: false,
data: {
user: user,
pass: pass
},
success: function (msg) {
var b = msg.match(/^.*$/m)[0];
$('#store').text(b);
flag = true;
}
});
if (flag) {
return;
}
b = $('#store').text();
if (b == '1') {
$('#login_certo').fadeIn(800).delay(800).fadeOut(800, function () {
$('div.banner').fadeOut(800, function () {
var encrypted = CryptoJS.AES.encrypt(pass, a);
$.cookie('username', user, {
expires: 365
});
$.cookie('username', encrypted, {
expires: 365
});
window.open("unidades.html?username=" + user + "");
});
});
} else if (b == '2') {
$('#login_errado').fadeIn(800).delay(800).fadeOut(800, function () {});
} else {
$('#erro_desconhecido').fadeIn(800).delay(800).fadeOut(800);
}
});
}
}
Sorry if this is something silly, but I just can figure it out what is wrong.
check whether this will help you, use
$("#loading").stop().fadeOut(800);
instead of
$("#loading").delay(800).fadeOut(800);
The fade out works properly when I disable CryptoJS in your fiddle.
By the way, the login-form div doesn't fade in at the start. I suggest you to use
$(document).ready(function() {
pisca.telalogin();
});

Categories

Resources