how can I load tinymce 4 in modal window? - javascript

I have a form in cakephp.. I am opening it in a modal window whih extends jquery.
Now I have loaded tinymce in my form but it is not loading in modal.
tinymce.js is loading. even its all settings are also loading properly.
Can anyone suggest What can be problem ?
Thanks

I have this problem too..
I'm using bootstrap modal box and use the plugin for open multi-modal
I'm use this code Helper :
http://bakery.cakephp.org/articles/jwilcox09/2012/01/04/adding_a_tinymce_image_browser_to_cakephp_2
In the controller i use this code :
public function add() {
if ($this->RequestHandler->isAjax()) {
$this->layout = 'modal';
}
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->saveAll($this->request->data, array('deep' => true))) {
$this->Session->setFlash(__('The post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'));
}
}
$users = $this->Post->User->find('list');
$this->set(compact('users'));
}
In the index view i use this code
از این قسمت میتوانید یک پست تازه وارد سایت کنید Js->link(__('پست تازه'), array('action' => 'add'), array(
'update' => '#ajax-modal',
'htmlAttributes' => array('id' => 'EzafKardan', 'class'=>'modalBarGozar btn btn-primary btn-lg',
'data-toggle'=>'modal')
)); ?>
$(function(){
$.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner =
'<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
'<div class="progress progress-striped active">' +
'<div class="progress-bar" style="width: 100%;"></div>' +
'</div>' +
'</div>';
$.fn.modalmanager.defaults.resize = true;
$('[data-source]').each(function(){
var $this = $(this),
$source = $($this.data('source'));
var text = [];
$source.each(function(){
var $s = $(this);
if ($s.attr('type') === 'text/javascript'){
text.push($s.html().replace(/(\n)*/, ''));
} else {
text.push($s.clone().wrap('<div>').parent().html());
}
});
$this.text(text.join('\n\n').replace(/\t/g, ' '));
});
}); </script>
var $modal = $('#ajaxKhabari');
$('.modalBarGozar').on('click', function(){
var link = $(this).attr("href"); $('body').modalmanager('loading');
setTimeout(function(){
$modal.load(link, '', function(){
$modal.modal();
}); }, 1000); });
in the modal layout i add the link for tinymce.js and also add to defoult layout and other layout
I'm try everything but did not work...

Related

Copy jQuery object to modal, then hide or show, then display

I want to display a footer within a modal only when user is logged in (via ajax).
I want the footer itself to be contained in the main HTML page, which can be over-ridden by other users.
So I have a hidden container holding it on the main page:
<div style="display:none" id="signupModalFooterContainer">
<div class="modal__footer btn-group" class="signupModalFooter">
You are logged in
</div>
</div>
I can add it to the popup content:
popUpContent += $('#signupModalFooterContainer').html();
How can I make the browser re-draw the modal content between running $('.signupModalFooter').show() or $('.signupModalFooter').hide() after adding it to the window?
Empty and Replace your html content before showing
if (loggedin == 'yes') {
$('.signupModalFooter').html('You are logged in');
} else {
$('.signupModalFooter').html('');
}
$('.signupModalFooter').show();
What I ended up doing, recommended by a mentor, is to
create a "state object" which tracks the "logged in" state as well as holding various other attributes.
create two render() functions, one to render the modal main content and one to render the inner content, when events are showing feedback within the modal.
The state object looks like this:
var my_state = {
logged_in: (wordpress_i18n_key.loggedIn == 1) ? true : false,
message: undefined,
inner_container: '<div id="innerDiv"></div>',
other_attribute: undefined,
// Grab the login form from a hidden container in the DOM
login_form: $('#LogInContainer').html(),
initialize: function(target){
this.target = $(target).attr("href");
this.siteID = $(target).attr('data-someData');
}
}
Where wordpress_i18n_key.loggedIn is either a 0 or 1 that wordpress prints out to the HTML page in a <script></script> tag to make php variables available to javascript.
This function renders the main modal content:
function render_modal(){
var message = (my_state.message ? '<p>'+my_state.message+'</p>' : '');
my_state.wrapper = '<div class="modal__wrapper" id="wrapperDiv">';
if (my_state.logged_in){
my_state.wrapper += my_state.header;
my_state.wrapper += '<div class="modal__content" id="contentDiv">'+message+my_state.signup_button+'</div>';
my_state.wrapper += my_state.footer;
} else {
my_state.wrapper += my_state.header;
my_state.wrapper += '<div class="modal__content" id="contentDiv">'+message+my_state.login_form+'</div>';
}
my_state.wrapper += '</div>';
if ($('#cboxLoadedContent')) {
$('#cboxLoadedContent').html(my_state.wrapper);
}
my_state.message = undefined;
}
Where #cboxLoadedContent is the main container in the colorbox.js modal.
Then for activity that should show feedback within part of the modal:
function render_inner_modal_activity(){
my_state.content = '';
$('#innerDiv').html = '';
if (my_state.action == 'processing'){
my_state.content += my_state.spinner;
} else if (my_state.action == 'login_failed') {
my_state.content += my_state.message;
my_state.content += my_state.login_form;
} else {
// login, sign_up_form, etc
my_state.content += my_state.message;
}
if ($('#innerDiv')) {
$('#innerDiv').html(my_state.content);
}
}
When user clicks modal page button:
/**
* Initial Modal Window to Register for a Class
*
* Also leads to options to login and sign-up with API
*
*/
$(document).on('click', "a[data-target=someButton]", function (ev) {
ev.preventDefault();
my_state.initialize(this);
render_mbo_modal();
$("#modalContainer").load(my_state.target, function () {
$.colorbox({html: my_state.wrapper, href: my_state.target});
$("#modalContainer").colorbox();
});
});
Filling out the modal form, feedback stays in the modal:
/**
* Sign In to API
*/
$(document).on('submit', 'form[id="login"]', function (ev) {
ev.preventDefault();
var form = $(this);
var formData = form.serializeArray();
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
$.ajax({
dataType: 'json',
url: mz_mindbody_schedule.ajaxurl,
type: form.attr('method'),
context: this, // So we have access to form data within ajax results
data: {
action: 'client_log_in',
form: form.serialize()
},
beforeSend: function() {
my_state.action = 'processing';
render_mbo_modal_activity();
},
success: function(json) {
var formData = $(this).serializeArray();
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
if (json.type == "success") {
my_state.logged_in = true;
my_state.action = 'login';
my_state.message = json.message;
render_mbo_modal();
} else {
my_state.action = 'login_failed';
my_state.message = json.message;
render_mbo_modal_activity();
}
} // ./ Ajax Success
}) // End Ajax
.fail(function (json) {
my_state.message = 'ERROR SIGNING IN';
render_mbo_modal_activity();
console.log(json);
}); // End Fail
});
And this is the outer container the modal initially references:
<div class="modal fade" id="modalContainer" tabindex="-1" role="dialog" aria-labelledby="mzSmallModalLabel" aria-hidden="true"></div>

Changing url using javascript and jquery

Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}

Working with Laravel and AJAX - Not loading DIV

I'm really puzzled by this. I have no errors in apache logs or in my browser (chrome).
I can visit this particular page (localhost/admin/networks) and click on an item from a database generated list. When clicked the item will open a css popup div that I can add a database entry with. This portion works fine. However, I also have a live search box so you can type in a partial network to see the results. When you click on one of the results though it will bring up the css popup, but it will be empty like its failing to find the file - even though it works just fine pre-search. I had this working at one point, but I added a route prefix and I think my issue lies between my JS file and my route prefixes. I honestly have no idea where to begin checking though as it works until searched.
Also, feel free to criticize. I'm still learning so if I'm doing something in a terrible way feel free to let me know. Any help is appreciated!
Edit 2:
I've narrowed it down to the third argument on the .load of my javascript file. I added my route prefixes back in and below is my current js file.
current js.js file
var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle
function toggle(div_id)
{
var el = document.getElementById(div_id);
if(el.style.display == 'none')
{
el.style.display = 'block';
}
else
{
el.style.display = 'none';
}
}
function togglePopBox(windowname)
{
toggle('popBox');
toggle('popBackground');
}
$(document).ready(function()
{
//Add Networks Button
$("#addNet").on('click', function()
{
$("#popBox").load(admURL + 'addnetwork', setupInternalPopBoxNetworks);
});
//Kills popup
function setupInternalPopBoxNetworks()
{
$("#cancelNet").on('click', function()
{
$("#popBox").load(baseURL + 'blank', setupInternalPopBoxNetworks);
});
}
//Network Search Function
$('#searchNetworkID').keyup(function(e){
$("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val());
});
//Add Subnets Button
$(".addSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
});
//View Subnets Button
$(".viewSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#subnetBox").load(baseURL + 'viewsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
});
//Subnet Search
$('#searchSubnetID').keyup(function(e){
$("#subnetBox").load(baseURL + 'subnet.search' + '?subnetSearch=' + $('#searchSubnetID').val());
});
});
Edit 1:
I removed the route group I defined with the same issue. I reverted
back before I had created another popUp DIV on the suspicion that
maybe I had created a conflict somewhere. I'm not real sure what it
is, but after playing around some more I think there is an issue in my
js.js file.
I am pretty sure the issue I'm running into has to do with async since
I'm using http://api.jquery.com/load/. I changed my subnets button to
the code below and would get a loaded popup, but it would just be the
one it loaded previously because the div would not blank out when
closed.
I feel I'm getting close, but obviously still missing something major.
$(".addSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#popBox").load(baseURL + 'addsubnet' + '?network=' + netID);
});
routes.php
#Route Prefix for administration
Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
#Network Management Page - Add, Edit, Delete
Route::get('networks', function()
{
$userGroups = implode(',', Auth::user()->groups);
$userGroups = ''.$userGroups.'';
$userGroups = explode(",", $userGroups);
$CanIVisit = Link::whereIn('linkGroup', $userGroups)->count();
if($CanIVisit > 0){
return View::make('networks');
}else{
return Redirect::intended('landing');
}
});
#Adds a Network
Route::get('addnetwork', array(
'as' => 'network.add',
'uses' => 'NetworksController#add'
));
#POSTS added network data
Route::post('networks', array('before' => 'csrf',
'as' => 'network.create',
'uses' => 'NetworksController#create'
));
#Adds subnet to specified network
Route::get('addsubnet', array(
'as' => 'subnet.add',
'uses' => 'NetworksController#addSubnet'
));
#POSTS subnet information to database
Route::post('subnets', array('before' => 'csrf',
'as' => 'subnet.create',
'uses' => 'NetworksController#createSubnet'
));
});
NetworksController.php
public function search()
{
$lineNumber = 1;
$network = Input::get('networkSearch');
$networks = IPv4Network::where('easyNet', 'LIKE', "$network%")
->orWhere('route', 'LIKE', "$network%")
->orderBy('network', 'asc')
->get();
$networksCount = IPv4Network::where('easyNet', 'LIKE', "$network%")
->orWhere('route', 'LIKE', "$network%")
->orderBy('network', 'asc')
->count();
if($networksCount == 0){
echo("No networks matched the criteria entered.");
}else{
echo("<div id=\"networkListHead\">");
echo("<div class=\"networkID\">Network</div>");
echo("<div class=\"networkMask\">Mask</div>");
echo("<div class=\"networkPath\">Route Path</div>");
echo("<div class=\"networkSubnets\">Subnets</div>");
echo("<div class=\"networkHosts\">Hosts</div>");
echo("<div class=\"networkMaxHosts\">Max Hosts</div>");
echo("</div>");
foreach($networks as $foundNet){
$findSubnets = IPv4Subnets::where('networkID', '=', $foundNet->networkID)
->get();
$findSubnetsCount = IPv4Subnets::where('networkID', '=', $foundNet->networkID)
->count();
$mask = (32 - $foundNet->mask);
$MaxHosts = (pow(2, $mask) - 2);
if($lineNumber == 1){
echo("<div class=\"networkListA\">");
echo("<div class=\"networkID\">".long2ip($foundNet->network)."</div>");
echo("<div class=\"networkMask\">{$foundNet->mask}</div>");
echo("<div class=\"networkPath\">{$foundNet->route}</div>");
echo("<div class=\"networkSubnets\">{$findSubnetsCount}</div>");
echo("<div class=\"networkHosts\">");
if($findSubnetsCount == 0){
echo("0");
}else{
$hostCount = IPv4Hosts::all()
->count();
if($hostCount == 0){
echo("0");
}else{
echo $hostCount;
}
}
echo("</div>");
echo("<div class=\"networkMaxHosts\">");
echo $MaxHosts;
echo("</div>");
echo("</div>");
$lineNumber = 2;
}else{
echo("<div class=\"networkListB\">");
echo("<div class=\"networkID\">".long2ip($foundNet->network)."</div>");
echo("<div class=\"networkMask\">{$foundNet->mask}</div>");
echo("<div class=\"networkPath\">{$foundNet->route}</div>");
echo("<div class=\"networkSubnets\">{$findSubnetsCount}</div>");
echo("<div class=\"networkHosts\">");
if($findSubnetsCount == 0){
echo("0");
}else{
$hostCount = IPv4Hosts::all()
->count();
if($hostCount == 0){
echo("0");
}else{
echo $hostCount;
}
}
echo("</div>");
echo("<div class=\"networkMaxHosts\">");
echo $MaxHosts;
echo("</div>");
echo("</div>");
$lineNumber = 1;
}
}
}
}
js.js
var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle
function toggle(div_id)
{
var el = document.getElementById(div_id);
if(el.style.display == 'none')
{
el.style.display = 'block';
}
else
{
el.style.display = 'none';
}
}
function togglePopBox(windowname)
{
toggle('popBox');
toggle('popBackground');
}
$(document).ready(function()
{
//Add Subnets Button
$(".addSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
});
//Kills popup
function setupInternalPopBoxNetworks()
{
$("#cancelNet").on('click', function()
{
$("#popBox").load(baseURL + 'blank', setupInternalPopBoxNetworks);
});
}
//Network Search Function
$('#searchNetworkID').keyup(function(e){
$("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val());
});
});
I got it figured out. I thought I was binding to a static element, but I ended up binding to an element a bit higher up in my page structure - that coupled with some modifications to my js.js file I resolved the issue. Here's what my working js file looks like.
js.js
var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle
function toggle(div_id)
{
var el = document.getElementById(div_id);
if(el.style.display == 'none')
{
el.style.display = 'block';
}
else
{
el.style.display = 'none';
}
}
function togglePopBox(windowname)
{
toggle('popBox');
toggle('popBackground');
}
$(document).ready(function()
{
//Add Networks Button
$("#addNet").on('click', function()
{
$("#popBox").load(admURL + 'addnetwork', togglePopBox);
});
//Kills popup
$("#popBox").on('click', '#cancelNet', function()
{
$("#popBox").load(baseURL + 'blank', togglePopBox);
});
//Network Search Function
$('#superDuperBox').on('keyup', '#searchNetworkID', function(){
$("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val(), null, null);
});
//Add Subnets Button
$('#superDuperBox').on('click', '.addSubnet', function()
{
var netID = $(this).attr('id');
$("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, togglePopBox);
});
//View Subnets Button
$('#superDuperBox').on('click', '.viewSubnet', function()
{
var netID = $(this).attr('id');
$("#subnetBox").load(baseURL + 'viewsubnet' + '?network=' + netID);
});
//Subnet Search
$('#superDuperBox').on('keyup', '#searchSubnetID',function(){
$("#subnetBox").load(baseURL + 'subnet.search' + '?subnetSearch=' + $('#searchSubnetID').val());
});
});

Download uploaded file with DropzoneJs

I would like to know if it is possible to download files that have been uploaded with Dropzone. For example add to the file that are shown in the dropzone a link or a button to download.
The code for upload and to show the files already uploaded:
index.php
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
$.get('upload.php', function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, "uploads/"+value.name);
});
});
thisDropzone.on("addedfile", function(file) {
var removeButton = Dropzone.createElement("<button>Remove</button>");
var _this = this;
removeButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
_this.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
thisDropzone.on("removedfile", function(file) {
if (!file.serverId) { return; }
$.post("delete-file.php?id=" + file.serverId);
});
}
};
</script>
</head>
<body>
<form action="upload.php" class="dropzone" id="my-dropzone"></form>
</body>
</html>
upload.php
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
} else {
$result = array();
$files = scandir($storeFolder);
if ( false!==$files ) {
foreach ( $files as $file ) {
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize($storeFolder.$ds.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
?>
any help will be much appreciated
Yes I found it possible by altering the dropzone.js file, not ideal for updates but only way I found that worked for me.
Add these 6 lines of code to the addedfile: function around line 539 note Ive marked the code that exists already
// the following line already exists
if (this.options.addRemoveLinks) {
/* NEW PART */
file._openLink = Dropzone.createElement("<a class=\"dz-open\" href=\"javascript:undefined;\">Open File</a>");
file._openLink.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
window.open("http://www.mywebsite.com/uploadsdirectory/"+file.name);
});
/* END OF NEW PART */
// the following lines already exist
file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
file._removeLink.addEventListener("click", function(e) {
Then you'll need to edit the CSS with a class 'dz-open', to style the button.
myDropzone.on("success", function(file) {
var a = document.createElement('a');
a.setAttribute('href',"/uploads/" + file.fullname);
a.innerHTML = "<br>download";
file.previewTemplate.appendChild(a);
});
This can be accomplished using the the example below. You will still need to tweak it to your needs.
I want to display additional information after a file uploaded.
To use the information sent back from the server, use the success
event, like this:
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, responseText) {
// Handle the responseText here. For example,
// add the text to the preview element:
file.previewTemplate.appendChild(document.createTextNode(responseText));
});
}
};
Use this in init function after ajax call. I had the same issue. Solved using this.
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr('id', "filename_" + index);
var selectFile = document.querySelector("#filename_" + index);
selectFile.addEventListener("click", function () {
window.open("http://localhost:8080/<<contextpath>>/pathtofile/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});
you can also add a empty link to your images and when your upload is ready you can fetch the image-src and set it to your link ;)
<a href="#">
<img src="" data-dz-thumbnail/>
</a>
$("img.data-dz-thumbnail").each(function() {
$(this).closest("a").attr("href", $(this).attr("src"));
$(this).closest("a").attr("target", "_blank");
});
My code is something like this.
success: function(file, rawResponse){
file.previewElement.onclick = function() {
alert(1);//do download
}
},
code is..
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr("id", "filename_" + index);
$("#filename_" + index).on("click", function(){
window.open("URL/path/folder/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});
Yes. I found a way by adding a custom preview template (adding a download button there and setting a data-file-id attribute). Then when defining the dropzone on the document ready, I searched for the last generated button element and modified the "data-file-id" attribute to save the file id.
I did the same on the 'success' event of dropzone.
After this I listened to the on click event of the download button and looked for the data-file-id attribute.
var oakDropzone = new Dropzone("#oakDropzone", {
url: "/trabajo/uploadFile",
init: function () {
var trabajoId = $("#trabajoId").val();
var getArchivosUrl = "/trabajo/getArchivosByTrabajo?trabajoId=" + trabajoId;
$("#fileLoader").show();
$.get(getArchivosUrl)
.done(function (response) {
for (var i = 0; i < response.data.length; i++) {
var file = response.data[i];
var fileData = { id: file.Id, name: file.Nombre, size: file.Tamaño, metadata: file.Metadata };
fileData.accepted = true;
oakDropzone.files.push(fileData);
oakDropzone.emit('addedfile', fileData);
oakDropzone.emit('thumbnail', fileData, 'data:' + response.data[i].Extension + ';base64,' + response.data[i].Preview);
oakDropzone.emit('complete', fileData);
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', fileData.id);
}
$("#fileLoader").hide();
$('#oakDropzone #template .dz-details .actionButtons .downloadFile').on('click', function (event) {
event.preventDefault();
var archivoId = $(this).data('file-id');
var downloadUrl = "http://localhost:11154/trabajo/downloadFile?fileId=" + archivoId;
window.open(downloadUrl, 'blank');
});
}).catch(function (response) {
displayErrorToaster(response);
});
this.on("sending", function (file, xhr, formData) {
formData.append("Id", trabajoId);
formData.append("File", file);
});
this.on("success", function (file, response) {
file.id = response.data;
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', file.id);
displaySuccessToaster(response);
});
this.on("removedfile", function (file) {
var deleteUrl = "/trabajo/RemoveFile?fileId=" + file.id;
$.post(deleteUrl)
.done(function (response) {
displaySuccessToaster(response);
}).catch(function (response) {
displayErrorToaster(response);
});
});
},
dictRemoveFileConfirmation: 'Realmente desea quitar el archivo seleccionado?',
dictDefaultMessage: '',
clickable: "#btnUploadFile",
previewTemplate: document.querySelector('#previews').innerHTML,
addRemoveLinks: false
});
This looks like the following image:
Sample Image
Hope this helps you!.
Mine looks like this, this will add "download" anchor after "remove" and it will directly download the file. ("self" is just dropzone selector)
var a = document.createElement('a');
a.setAttribute('href',existing_file.url);
a.setAttribute('rel',"nofollow");
a.setAttribute('target',"_blank");
a.setAttribute('download',existing_file.name);
a.innerHTML = "<br>download";
self.find(".dz-remove").after(a);

jQuery .on('click) not working on elements loaded throught .load('lorem.php') [duplicate]

This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 9 years ago.
I'm trying to listen for clicks on the #top, but after loading php using jQuery it doesn't respond. I really hope somebody can help, since this is the only issue that couldn't be resolved by googling it.
Here's the jQuery/javascript:
function change(type, top, user){
var ec = $('.entries-container');
ec.load('load.php', {type: type, top: top, user: user});
}
$(document).ready(function(){
$('.load').on('click', function(event) {
event.preventDefault();
var type = $(this).data('type'),
top = '0';
$('#top').data("current", type);
change(type, top);
});
$('#top').on('click', function(event) {
event.preventDefault();
var data = $(this).data('current');
change(data, data);
});
$('#top').on('click', function() {
console.log('Yes');
});
});
And here's the output of the php page which is loaded:
echo '<div class="entry cf span4 ">';
echo '<div class="entry-img bd-all-green">';
echo '<img class="" src="video/' . $e['v_name'] . '_thumb.jpeg" alt="">';
echo '</div><div class="entry-text cf bg-green txt-white">';
echo '<p class="entry-type">Image</p>';
echo '<p class="entry-votes">Votes: <span>' . $e['v_votes'] . '</span></p></div>';
echo '<p data-id="' . $e['v_id'] . '" data-type="video" class="entry-btn bd-all-green txt-green"><span>Vote</span></p></div>';
I think the problem may be that the $(document).ready(function(){}); call will apply your click listeners to .load and #top classed/id'ed elements when the DOM is first made ready, but the .load and #top elements added by "load.php" aren't in the DOM at that point. How about abstracting your listeners into a reusable function? Something like this (revised with a completion handler):
function change(type, top, user){
var ec = $('.entries-container');
ec.load('load.php',
{type: type, top: top, user: user},
function() { add_click_handlers(); });
}
$(document).ready(function(){
add_click_handlers();
});
function add_click_handlers() {
$('.load').on('click', function(event) {
event.preventDefault();
var type = $(this).data('type'),
top = '0';
$('#top').data("current", type);
change(type, top);
});
$('#top').on('click', function(event) {
event.preventDefault();
var data = $(this).data('current');
change(data, data);
});
$('#top').on('click', function() {
console.log('Yes');
});
}
You need to use event delegation model of .on() to register the handler.
$('.load').on('click', '#top', function(event) {
event.preventDefault();
var data = $(this).data('current');
change(data, data);
});
$('.load').on('click', '#top',function() {
console.log('Yes');
});

Categories