Fancybox thumbnail on AJAX - ajax

I am using fancybox gallery, that I am loading dynamically. I have always one picture with data-fancybox attribute and with ID.
JS is like this:
$('[data-fancybox]').each(function(e){
var idgal = $(this).data("fancybox");
$(this).fancybox({
loop: false,
onInit: function (instance) {
$.ajax({
type: 'POST',
url: '/loadGallery.php?gallery='+idgal,
dataType: 'json',
success: function (data) {
$.each(data, function (index,src) {
instance.addContent({
'type': 'image',
'src': src.src
});
});
}
});
},
thumbs: {
autoStart: true,
axis : 'x'
}
})
})
Problem is, that I don't get thumbnails of dynamically loaded images. Any ideas? Thanks!

If you ask for the last fancyBox (v 3.5.7), to get thumbnails you also need to proceed thumbnails URL (inside options/opts key). And, most important, at the end, need to reinitialize thumbs (eg. after each loop inside Ajax success block).
Here is only part from your example with changes:
// Ajax success
success: function ( data ) {
$.each(data, function (index, src) {
instance.addContent({
'type': 'image',
'src': src.src,
'opts': {
'thumb': 'thumb.jpg' // thumbnail url (eg. src.opts.thumb)
}
});
});
// reinitialize Thumbs
instance.Thumbs.init(instance);
// optional: to get thumbs autoStart
instance.Thumbs.show();
} // success

Related

Wordpress: Using AJAX to populate tinymce dropdown for use in a shortcode

To cut a long story short...
I am trying to dynamically populate a tinymce dropdown with a list of posts and the title to aid selection.
The various parts work, I can get my data with AJAX, I can make a dropdown using hardcoded text. How do I get the results of the AJAX call into the menu parameter in the tinymce.addButton method?
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {action : 'testimonial_list'},
success: function(data){
console.log(data);
// I now have the array to populate;
//{"Senior Advisor for Education Scotland":137,"Group HRD":117,"Utilities Director":118,"COO G4S":120,"MD Lexmark":60,"Human Resource Director, Connaught plc":55}
}
});
(function() {
tinymce.PluginManager.add('my_mce_button', function( editor, url ) {
editor.addButton( 'my_mce_button', {
text: 'Testimonials',
icon: false,
type: 'menubutton',
menu: [
// FOR EACH data KEY VALUE PAIR
{
text: //data ITEM KEY,
onclick: function() {
editor.insertContent('[my_shortcode id = //data VALUE]');
}
},
... // MORE ROWS
]
});
});
})();

Summernote Show Images that have been uploaded to a folder

I am using the really nice Summernote Editor for a little webapp.
Instead of using the default inline base64 code for images I am storing the images in a folder.
I have that part working as intended. I am able to click the "image" icon and select an image and it will upload it to a folder on my server in its original type (jpg, png, gif).
The problem is that even though the image gets uploaded properly, Summernote does not add it to the editor ... so it doesn't show.
Here is the relevant code I am using:
$(function() {
$('.summernote').summernote({
lang: 'en-EN',
height: 500,
onImageUpload: function(files, editor, $editable) {
sendFile(files[0],editor,$editable);
}
});
function sendFile(file,editor,welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
url: "uploader.php",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
editor.insertImage(welEditable, data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus+" "+errorThrown);
}
});
}
});
The uploader.php file looks like this:
<?php
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['file']['tmp_name'],
'images/'.$_FILES['file']['name'])){
$tmp='images/'.$_FILES['file']['name'];
echo 'images/'.$_FILES['file']['name'];
//echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
?>
Any ideas as to why the Summernote editor will not show the saved (stored) images in the editor?
Thanks
In the new version of summernote onImageUpload callback is called only with files argument. It means that editor is not available.
You can insert an image with:
$('.summernote').summernote("insertImage", url, filename);
In your case:
$('.summernote').summernote("insertImage", data, 'filename');
I did it using codeigniter may be this help someone.
$(function() {
$('.summernote').summernote({
onImageUpload: function(files, editor, $editable) {
sendFile(files[0],editor,$editable);
}
});
function sendFile(file,editor,welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
url: "http://localhost/fourm/media/editorupload",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
editor.insertImage(welEditable, data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus+" "+errorThrown);
}
});
}
});
You must use "callbacks: {}" method. like this:
$('.summernote').summernote({
height: 500,
tabsize: 4,
callbacks: {
onImageUpload: function(files, editor, $editable) {
console.log('onImageUpload');
sendFile(files[0],editor,$editable);
}
}});

fetching json data using ajax

Somebody please advice on why $.Ajax that am trying to use fetching webApi data is not working but $.getJSON one is working.I would wish to use $.Ajax instead of $.getJSON.
Both codes are here below.
This one works
var uri = 'api/products';
// Send an AJAX request
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
...........................................
This does not work.
var uri = 'api/products';
// Send an AJAX request
$(document).ready(function () {
$.ajax({
url: 'api/products',
type: 'GET',
datatype: 'json',
cache: 'false',
success:function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
}
});
});

Ajax - prevent click on a successful ajax request

I have a video thumbnail on my page, with a little icon "Thumbs Down". When you click on that, another thumbnail shows, replacing the other. User can do that as much as they want.
My code is now working only the first time. HTML:
AJAX:
$('.dislike_black').click(function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
When I click the icon the first time, its all fine, triggers the alert, the second time thought, no alert, and the browser is loading the href link.
I tried .preventDefault(); on the success and the complete event, but its not working.
Any hint on how to do this?
Your content is dynamically created so, depending on the version of jQuery you are using, you need the jQuery.live() or jQuery.on() method
jQuery.live() since jQuery 1.3 an event handler for all elements which match the current selector, now and in the future.
jQuery.on() since jQuery 1.7 - Attach an event handler function for one or more events to the selected elements.
Sample
jQuery.live()
$('.dislike_black').live("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
jQuery.on()
$('.dislike_black').on("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
More Information
jQuery.live()
jQuery.on()
Because you are replacing the dom which contains the anchor itself by new html in the ajax success handler. In this case you should use on which will attach event handler to parent or document element whatever you pass as the root element but will trigger the event only on the matching selector which you pass as the second argument. Try this.
$(document).on('click', '.dislike_black', function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
.on() reference: http://api.jquery.com/on/ (Ver. 1.7+)
If you are using older version of jQuery you can still achieve this using delegate method whose syntax is same as on but just the first 2 arguments are interchanged.
$(document).delegate('.dislike_black', 'click', function(e) {
//Your code here
});
.delegate() reference: http://api.jquery.com/delegate/
try
$(document).delegate('.dislike_black',"click",function(e) {
Try using event delegation.
// older jquery, use this line:
// $( ".dislike_black" ).live( "click", function ( e ) {
$( document ).on( "click", ".dislike_black", function ( e ) {
e.preventDefault();
alert( "test" );
var $aTag = $( this );
$.ajax( {
url : $aTag.attr( 'href' ),
type : "POST",
data : {
"sort" : $aTag.data( 'sort' ),
"page" : $aTag.data( 'page' )
},
success: function ( response ) {
$aTag.parents( "li" ).replaceWith( response );
}
});
});

Displaying a message in a dialog box using AJAX, jQuery, and CakePHP

I have a form, and when users submit this form, it should pass the data along to a function using AJAX. Then, the result of that is displayed to the user in a dialog box. I'm using CakePHP (1.3) and jQuery to try and accomplish this but I feel like I'm running into the ground.
The form will eventually be used for uploading images with tags, but for now I just want to see a message pop up in the box..
The form:
<?php
echo $this->Form->create('Image', array('type' => 'file', 'controller' => 'images',
'action' => 'upload', 'method' => 'post'));
echo $this->Form->input('Wallpaper', array('type' => 'file'));
echo $this->Form->input('Tags');
echo $this->Form->end('Upload!');
?>
The AJAX:
$(document).ready(function() {
$("#ImageUploadForm").submit(function() {
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
$("#dialog-modal").dialog({
$("#dialog-modal").append("<p>"+html+"</p>");
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
})
}
});
return false;
});
});
NOTE: if I put $("#dialog-modal").dialog({ height: 140, modal: true }); OUTSIDE of the $.ajax but inside the $("#ImageUploadForm").submit(function() { and comment out the $.ajax stuff, I WILL see a dialog box pop up and then I have to click it for it to go away. After this, it will not forward to the location /images/upload/
The method that AJAX calls:
public function upload()
{
$this->autoRender = false;
if ($this->RequestHandler->isAjax())
{
echo 'Hi!';
exit();
}
}
$this->RequestHandler->isAjax() seems to do either absolutely nothing, or it is always returning false. I have never entered an if statement with that as the condition.
Thanks for all the help, if you need more information let me know.
Try this:
$(document).ready(function(){
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
//First you must append to div:
$("#dialog-modal").append("<p>"+html+"</p>");
$("#dialog-modal").dialog({
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
}); //dialog
}//success
});//ajax
Note the first sentence:
$("#dialog-modal").append("<p>"+html+"</p>");
it can not be a propertie. You must pass an object as a parameter to dialog() function so properties or member of an object looks like:
{
height:140,
buttons:{},
anotherPropertie: 'value'
}
If you call to dialog() function after ajax(), the dialog will be empty because will execute before success() function declared inside ajax().

Resources