CKEditor - Custom image browser - php

I'm currently developing a image browser in PHP and jQuery. I've managed to create a custom button plugin that opens my image browser in a new window (not a dialog box):
CKEDITOR.plugins.add('imgbrowser',
{
init: function(editor)
{
var pluginName = 'imgbrowser';
editor.ui.addButton('Imgbrowser',
{
label: 'Image browser',
command: pluginName,
click: function (editor) { window.open('/publish/browser/index.php','Image Browser','width=900,height=600'); }
});
}
});
Is there anyone here who knows how to enable the callback function and how this will be used so that I can add the selected pictures into the editor?

Ok. Here is the answer:
In the parent window I have this function:
function InsertHTML(file_path)
{
// Get the editor instance that we want to interact with.
var oEditor = CKEDITOR.instances.page_content;
var value = file_path;
// Check the active editing mode.
if ( oEditor.mode == 'wysiwyg' )
{
// Insert the desired HTML.
oEditor.insertHtml( '<img src="' + value + '" />' );
}
else
alert( 'You must be on WYSIWYG mode!' );
}
page_content is the id of my textarea.
In the popup window I have this function:
function sendToParent(file_path) {
window.opener.InsertHTML(file_path);
}
echo "<input type='button' value='Insert image' onclick='sendToParent(\"".$img_element."\")' />"

Related

Wordpress - Get an image using the media library

I'm creating a plugin and i have an admin page
In the options of that page, i would like to add a button that allow me to open the Wordpress media library and select an image from it, after that, get the URL of the selected image and the alt attribute.
If it is possible, how can i do that using AJAX?
First you would need to enqueue wordpress core media scripts and a custom js script
function my_enqueue_media_lib_uploader() {
//Core media script
wp_enqueue_media();
// Your custom js file
wp_register_script( 'media-lib-uploader-js', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array('jquery') );
wp_enqueue_script( 'media-lib-uploader-js' );
}
add_action('admin_enqueue_scripts', 'my_enqueue_media_lib_uploader');
Then let say you have this markup within your options page: an upload button and a text input to store the selected image url
<form method="post">
<input id="image-url" type="text" name="image" />
<input id="upload-button" type="button" class="button" value="Upload Image" />
<input type="submit" value="Submit" />
</form>
You need to add this javascript code to invoke the uploader popup
jQuery(document).ready(function($){
var mediaUploader;
$('#upload-button').click(function(e) {
e.preventDefault();
// If the uploader object has already been created, reopen the dialog
if (mediaUploader) {
mediaUploader.open();
return;
}
// Extend the wp.media object
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
}, multiple: false });
// When a file is selected, grab the URL and set it as the text field's value
mediaUploader.on('select', function() {
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#image-url').val(attachment.url);
});
// Open the uploader dialog
mediaUploader.open();
});
});
Once the image is selected, your image-url input will now contain the url and will be saved on form submit.
The use case is: I have plugin that contain index.php as main file, I want to be able to click on a button and the media library opened and select an image from it, this image should be load into an image tag.
1- add script to your main PHP plugin
// index.php
// ...
// add script js for page
add_action('admin_enqueue_scripts', function () {
// Enqueue WordPress media scripts
if ($_GET["page"]== 'debug_area') {
wp_enqueue_media();
// Enqueue custom script that will interact with wp.media
wp_enqueue_script(
'myprefix_script',
plugins_url('/load_img.js', __FILE__),
array('jquery'),
'0.1');
}
});
// add ajax action to get the image async
add_action('wp_ajax_get_image_from_media_lib', function () {
if (isset($_GET['id'])) {
$image = wp_get_attachment_image(
filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT),
'medium',
false,
array('id' => 'image_preview')
);
$data = array(
'image' => $image,
);
wp_send_json_success($data);
} else {
wp_send_json_error();
}
});
2- add file JS that already included in enqueue
// load_img.js
jQuery(document).ready(_ => {
console.clear();
/**
* Define media_lib_frame as wp.media object
*/
const media_lib_frame = wp.media({
title: 'Select Media',
multiple: false,
library: {
type: 'image',
}
});
/**
* On close, get selections and save to the hidden input
* plus other AJAX stuff to refresh the image preview
*/
media_lib_frame.on('close', _ => {
const selection = media_lib_frame.state().get('selection');
const gallery_ids = selection.map(attachment => attachment['id']);
const ids = gallery_ids.join(",");
jQuery('input#idImage').val(ids);
loadImage(ids);
});
/**
* On open, get the id from the hidden input
* and select the appropriate images in the media manager
*/
media_lib_frame.on('open', _ => {
const selection = media_lib_frame.state().get('selection');
const ids = jQuery('input#idImage').val().split(',');
ids.forEach(id => {
const attachment = wp.media.attachment(id);
attachment.fetch();
selection.add(attachment ? [attachment] : []);
});
});
jQuery('button#btnOpenMediaLibFrame').click(e => {
e.preventDefault();
media_lib_frame.open();
});
});
// Ajax request to refresh the image preview
const loadImage = the_id => {
const data = {action: 'get_image_from_media_lib', id: the_id};
jQuery.get(ajaxurl, data, response => {
if (response.success === true) {
jQuery('#image_preview').replaceWith(response.data.image);
}
});
}
3- add this HTML into the function that responsible for render view
<img id="image_preview"/>
<input
type="hidden"
id="idImage"
class="regular-text"/>
<button
type='button'
class="button-primary"
id="btnOpenMediaLibFrame">
Select a image
</button>

Create a jquery ajax image organizer

I want to create a button on imperavi's redactor, that will display uploaded files (only photos) in a modal, that i previously uploaded, and i will allow the user, to organize this photos, order their order and organize them in folders, and create folders. And when the user select the photo, the tag is inserted in the text field (redactor).
I rely want a place to begin, or a already existing solution, my knowledge with php is big but my jquery and ajax is very small
I don't want to display the computer folder, i want to display the images int the database
Sorry for the bad English.
Where do i begin?
edit 1:
I manged to add the button
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {};
RedactorPlugins.myPlugin = {
init: function() {
this.addBtn('myMethod', 'Add Image', function(obj) {
obj.myMethod();
});
},
myMethod: function()
{
// callback (optional)
var callback = $.proxy(function()
{
return 1;
}, this);
var modal = String() +
'<div id="redactor_modal_content">' +
'<div class="modal-body">' +
'<p>One fine body...</p>' +
'</div>' +
'<div id="redactor_modal_footer">' +
'Close' +
'Save changes' +
'</div>' +
'</div>';
// 500 it is the width of the window in pixels
// or call a modal with a code
this.modalInit('<h3>Modal header</h3>', modal, 500, callback);
// call a modal from element with ID #mymodal
//this.modalInit('<h3>Modal header</h3>', '#mymodal', 500, callback);
}
}

Changing Hidden input with Href Javascript call

I am writing a page that grabs images from a url the user inputs, and using ajax, am updating a div with the img src to be displayed by fancybox in a modal window. The images that are displayed have titles displayed below, as links. This is done with fancybox (If you set the title as set the title="something" will display "something" below the image. If you set the title as title="<a href='something.html'>Something</a>)
My problem is this. I need to allow the user to choose an image by clicking the link, and in turn have it do 2 things: update the hidden field with the src url of the img, and submit the form.
Here is the code I have for the ajax request:
function getCustomerInfo() {
var phone = document.getElementById("urls").value;
var url = "grabimages.php?urls=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
$("#dvloader").show();
$("#selectimages").hide();
//$("#noimages").hide();
function updatePage() {
if (request.readyState == 4)
if (request.status == 200){
if(request.responseText == ''){
$("#dvloader").hide();
$("#noimages").show();
}else{
document.getElementById("update-div").innerHTML = request.responseText;
$("#dvloader").hide();
$("#selectimages").show();
$(".fancybox")
.attr('rel', 'gallery')
.fancybox({
padding : 15
});
$('input[id=theimage]').click(function(){
$(".fancybox").eq(0).trigger('click');
});
function recURL(recipeurl) {
$('#recipeurl').val('recipeurl');
document.recipeform.submit();
}
}
}else{
alert('nothing');
}
}
And here is the code I tried for the href javascript call (this is the server side code, so PHP:
echo "<a class=\"fancybox\" id=\"recipelinks\" title=\"<img src=\"" . $imagepath . "\" alt=\"\"/>";
This doesn't do anything. Any suggestions?
Use $('.fancybody').live('click', function() { });, live allows you to listen for events on elements which are added to the DOM dynamically.

jCarousel initializing/refreshing/reloading each time clicked on image

I am making a picture preview with jCarousel (http://sorgalla.com/projects/jcarousel/), but faced with one problem: I do not know how could I reload/refresh jCarousel dynamic list.
I have few categories of images. When I click on a picture in one of that, I need that the list would be created and preview start with that element. I have some code, but do not know how to make it re-create all list after clicking on other image that preview start with other image.
Here are my code:
$(document).ready(function(){
$("ul#stage li").live('click', function() {
var ul = $(this).parent();
var index = +(ul.children().index(this))+1;
var mycarousel_itemList = [ ];
$('li[data-id]').each(function () {
var $this = $(this);
mycarousel_itemList.push({
url : $this.attr("data-img"),
title : $this.attr("data-title")
});
});
function mycarousel_itemLoadCallback(carousel, state) {
for (var i = carousel.first; i <= carousel.last; i++) {
if (carousel.has(i)) {
continue;
}
if (i > mycarousel_itemList.length) {
break;
}
carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i-1]));
}
};
function mycarousel_getItemHTML(item) {
return '<img src="' + item.url + '" width="800" height="600" alt="' + item.url + '" />';
};
alert(index);
jQuery('#mycarousel').jcarousel({
itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback},
size: mycarousel_itemList.length,
scroll: 1,
start: index,
wrap: 'last',
animation: 'fast',
visible: 1
});
document.getElementById('popup-content').style.background='url('+$(this).attr("data-img")+') no-repeat center';
document.getElementById('fades').style.display='block';
document.getElementById("light").style.display = "block";
$("#light").fadeTo("slow", 1);
});
});
Everything is like that: there are images > I click on one of those > popup shows with jCarousel and one visible image and then I could scroll through all other images.
It is working good, but just a first time. When I click on other image (after closing popup), the view starts with that image which was opened last.
If something are not clear enough - please, ask. I will try to make it more precisely.
Thanks for your help!
You can recreate jCarousel, first use $('#mycarousel').remove(); and next init jCarousel again. I didn't really understand what you're trying to do, but this can help in most cases, of course jCarousel should have Destroy method but it hasn't.
And why you don't use jquery selectors in some cases?

Php/ajax files uploading: hidden iframe loads more than once

My problem occurs, when I upload images with ajax. Ajax response comes to a hidden iframe, and for debug I echo it (uploaded image name) here and then alert it. So when I upload the first image - there's one alert, as it should be. When I upload the 2nd - I see 2 alerts. The 3rd - 3 alerts. And so on. It means, that my iframe reloads as many times, as the order number of the file being just uploaded.
Interesting, that the names in alerts after each file upload are always the same. For example, 2 times "mySecondImage.jpg", 3 times "myThirdImage.jpg"...
What can be done to solve the problem? Thanks.
// FUNCTION - AJAX FILE UPLOADER
// this function creates new elements, but only in case, when user uploads files
$.fn.fileUploader = function ( $inputName ) {
var $body = $(this);
var $form = $body.parents('form');
var $fileInput = $body.find(':file');
// after file is uploaded, we need the file input to be empty again
var $fileInputEmpty = '<input type="file" name="' + $inputName + '" />';
var $iframe = $('#ajaxResult');
// user submits the form
$form.submit( function() {
// check the result
$iframe.load( function () {
var $response = $iframe.contents().find('body').html();
alert($response); // debug
// add new content image
$output = createUpdateImage( $response, $('[name="imageLinkURL"]').val() );
// add new element
addNewElement( $output );
// success
if ( $response.length ) {
$fileInput.replaceWith( $fileInputEmpty );
$fileInput = $body.find(':file');
}
});
}); // form submit
};
$('.fileUploder').each(function () {
var $inputName = $(this).find(':file').attr('name');
$(this).fileUploader( $inputName );
});
Well, the glitch is fixed!
I slightly rewrote the jQuery function:
...
// user submits the form
$form.submit( function() {
var $response = '';
$iframe.load( function () {
$response = $iframe.contents().find('body').html();
});
// periodically check the result in iframe
var $timer = setInterval( function() {
if ( $response != '' ) {
clearInterval( $timer );
// do all required actions
}
}, 100 );
}); // form submit
...
$form.submit( function() {
$iframe.load( function () {
I think the problem is here. On form submit you add an event "on load". So it called 1 time, then 2 times, etc. Maybe removing the first of these two strings can help (use only load event handler).

Categories