Im having trouble getting my CKEditor to work properly.
I am inserting my instance using Jquery. And set up my own Ajax save function for the editor.
My instances are always inserted just fine. The editor appears as it should, - and seem to work.
HOWEVER: it turns out that the 2. time I insert the instance, - the textarea is not being updated - thus no updated data sent to the Ajaxcall. It sends the old data.
After sending to the ajax call, I destroy my instance:
CKEDITOR.instances[currentInstance].destroy();
And the editor seem to be destroyed properly, every time.
OnClick I then re-insert the editor (Same instancename. I also remove the textarea when I destroy the instance, and then reinsert the textarea, when I reinsert the instance. Same textareaname).
Can anyone tell me why I can insert the instance again and again, - but the editor only updates the textarea the first time?
Ive tried:
for ( var instance in CKEDITOR.instances ) {
CKEDITOR.instances[instance].updateElement(); }
inserted in the save function - just before the ajaxcall. But still no update.
This is the build of the instance. Via Jquery I insert this as html() :
<script type="text/javascript">
CKEDITOR.replace('tekstindhold233',
{ height:'250px',width:'575px' });
</script>
And heres the savefunction:
CKEDITOR.plugins.add('popwebsave',
{
init: function(editor)
{
var pluginName = 'popwebsave';
editor.addCommand( pluginName,
{
exec : function( editor )
{
for ( var i in CKEDITOR.instances ){
var currentInstance = i;
break;
}
for ( var instance in CKEDITOR.instances ) {
CKEDITOR.instances[instance].updateElement(); }
var sprog = $('#lan_holder').text();
var vis = $('#vis_holder').text();
var pageId = $('#pageId_holder').text();
var tekstIndhold = CKEDITOR.instances[currentInstance].getData();
var tekstIndholdBox = currentInstance.replace('tekstindhold','');
var contentOrden = $('#content_orden' + tekstIndholdBox).text();
var dataString = 'lan=' + sprog + '&tekstindhold=' + tekstIndhold + '&eid=' + tekstIndholdBox + '&vis=' + vis + '&id=' + pageId + '&contentOrden=' + contentOrden;
$("#tekstindhold_box" + tekstIndholdBox).animate({
opacity: 0
} , {
duration: 500,
complete: function() {
$("#textarea_box" + tekstIndholdBox).text('');
$.ajax({
type: "POST",
url: "includes/JQ_opdater_tekst.php",
data: dataString,
dataType: "json",
cache: false,
success: function(databack){
$("#textarea_box" + tekstIndholdBox).animate({
height: 100
}, 500, function() {
$("#tekstindhold_box" + tekstIndholdBox).html(databack.tekstindhold_db);
$("#tekstindhold_box" + tekstIndholdBox).animate({
opacity: 1
}, 500, function() {
CKEDITOR.instances[currentInstance].destroy();
});
});
}
});
}
});
},
canUndo : true
});
/*
editor.addCommand(pluginName,
new CKEDITOR.dialogCommand(pluginName)
);
*/
editor.ui.addButton('Popwebsave',
{
label: 'Gem',
command: pluginName,
className : 'cke_button_save'
});
}
});
Nevermind!
I figured it out. Turns out that the instance needs to be present in the DOM, on destroy() I switched the order of events around so that destroy() happens first, and THEN removed the textarea. Works just fine now.
Related
I am performing an Ajax (JQuery) request on a php script which iterates. At each iteration I do an "echo" of the value of the loop counter, encoded in JSon. The goal is to manage the display of a progress bar.
By doing this I hoped to intercept and retrieve each of the counter values in a separate response thanks to the "progress" event.
Actually I only have one answer which contains all the counter values.
My research always leads me to information about downloading files, which is not my situation.
Maybe I should use the "onreadystatechange" event, but I don't see how to fit it into my code: $ Ajax parameter or separate function?
If anyone has an idea to solve my problem.
Here is my JS code
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
$("#xhr-rep").css("display", "block");
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var compteur = evt.text;
$("#xhr-rep").html(compteur);
}
}, false);
return xhr;
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}
After two days of fruitless research, I decided to join the community. I hope to get a solution. I develop a plug-in that, among other things, must implement the upload of documents. this should be done using ajax technology. the problem is that the request is approved, but admin_ajax.php reacts like no action was taken. Outside of wp this piece of code works fine, as it was thought out. The problems come with installing this code in wp. Below is my code
PHP. This code in the main class that will call from main modul of plugin
class main{
//other activation methods
private function register_scripts(){
add_action('wp_enqueue_scripts', array($this,'re_add_script'));
}
public function re_add_script() {
wp_enqueue_script('re_upload',plugins_url('re'.'/js/re_upload.js'),array('jquery'));
wp_localize_script('re_upload',"re_ajax",array(
'ajaxurl'=>admin_url("admin-ajax.php")));
add_action( 'wp_ajax_upload', 'processingUpload');
}
}//end of class
//callback function
function processingUpload(){
$clsUpload = new UploadsDocs();
$clsUpload->setRequestedData($_FILES,$_POST['doc_id']);
$clsUpload->checkUploadsFiles();
$clsUpload->outputFilesList();
wp_die();
}
jQuery 're_upload.js'
jQuery(document).ready(function (e) {
jQuery('#bt_upload').on('click', function () {
var toUpload=getFileListToUpload();
var form_data = new FormData();
var ins = input.files.length;
for (var x = 0; x < ins; x++) {
if (isFileToUpload(input.files[x],toUpload)){
form_data.append("files[]", input.files[x]);
}
}
form_data.append("doc_id", jQuery('#doc_id')[0].value);
var data_to_sent={
action: 'upload',
datas: form_data
};
jQuery.ajax({
url: re_ajax.ajaxurl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: data_to_sent,
type: 'post',
success: function (response) {
// do something
},
error: function (response) {
// do something
},
xhr: function(){
//upload Progress
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
jQuery('#bt_upload').css("display","none");
jQuery('#progress-wrp').css("display","block");
jQuery('#progress-wrp' +" .progress-bar").css("width", + percent +"%");
(percent<50)? jQuery('#progress-status').addClass('status-less-then-50'): jQuery('.status-less-then-50').removeClass('status-less-then-50').addClass('status-more-then-50');
jQuery('#progress-status').text("Uploading..."+percent +"%");
}, true);
}
return xhr;
},
mimeType:"multipart/form-data"
});
});
});
function getFileListToUpload(){
var list=[];
var elem = document.getElementsByClassName('preview');
var tag_li=elem[0].querySelectorAll('p');
for (var i=0;i<tag_li.length;i++){
list[i]=tag_li[i].textContent.split('(')[0];
}
return list;
}
function isFileToUpload(input_file,files_toUpload){
var res=false;
for(var i=0; i<files_toUpload.length;i++){
if (input_file.name==files_toUpload[i]){
res=true;
break;
}
}
return res;
}
The problem is
add_action( 'wp_ajax_upload', 'processingUpload');
is not called.
The upload is done in two separate invocations of the server. The first invocation displays the upload page to the user. The second invocation processes the AJAX request. Your call to
add_action( 'wp_ajax_upload', 'processingUpload');
is done in the first invocation where it is not needed but not in the second invocation where it is needed.
Please read https://codex.wordpress.org/AJAX_in_Plugins. (Observe carefully how the call to 'add_action( 'wp_ajax_...', ...) is done.) Further, you need to read about nonces.
Try to append action to your ajax url like:
url: re_ajax.ajaxurl?action=upload
and
data: form_data
or pass it to form_data like:
form_data.append('action', 'upload')
I am trying to figure out ways to prevent ajax from being called multiple times. Below is my code. I created a scrollable div, my goal is, once the scroll inside this div is about to reach the bottom, I want to call the ajax. Everything works so far. But the problem is, whenever I scroll the div fast enough to the bottom, the ajax is being called multiple times.
$('.scroll_div').scroll(function(){
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){
}
}).done(function(data){
alert(data);
});
}
});
I would put a timer on it - adjust the timeout accordingly, so that the ajax would only fire if the user stays put for a second or two:
$('.scroll_div').scroll(function(){
if(typeof(myTimer)!='undefined'){
clearTimeout(myTimer);
}
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
//timer
myTimer = window.setTimeout(function(){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){}
}).done(function(data){
alert(data);
});
}, 2500);
}
});
I have set up a test site using masonry and am using isotope for sorting.
I have also set up a button at the bottom that the user can click to ajax load more posts.
I have the ajax loading working properly, but when the new posts get appended to the bottom of the container the first four posts at the top all shift out of place. If I keep clicking 'load more' all subsequent posts that load load perfectly and nothing else shifts. It seems to be only the first four posts, on the first ajax load.
Anyone know why this is happening?? It's driving me crazy
Ajax Load File
// ajaxLoop.js
jQuery(function($){
var page = 1;
var loading = true;
var $window = $(window);
var $ajaxLoadMoreButton = $("body.blog .ajaxLoadMoreButton");
var $content = $("body.blog #container");
var load_posts = function(){
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page},
dataType : "html",
url : "wp-content/themes/twentytwelve/loopHandler.php",
beforeSend : function() {
if(page !=1) {
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
$content.append($data).masonry('reload');
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$ajaxLoadMoreButton.click(function() {
loading = true;
page++;
load_posts();
});
});
To anyone else having this issue, after digging for hours through documentation and asking for help on SO and other sites, I have resolved the issue. The issue apparently lies within -webkit browsers and the transform property that is placed on masonry elements after appending new ones.
I used this as a reference:
http://isotope.metafizzy.co/docs/help.html#disabling_transforms
and then I used this code to disable all transforms on elements:
$("#container").isotope({
itemSelector : ".brick",
transformsEnabled: false, // disables all transform properties
getSortData : {
name : function () {
$tag = $("#container").find("a[rel=tag]").text();
}
}
});
I posted this question AJAX URL update as I thought the problem with my code was with AJAX but I think this could be an issue with HighStocks.
I have an external .js file with these functions:
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {
$.ajax({
type: 'post',
url: 'http://...' + ticker + '....com',
success: function (data, status) {
//chart is rendered in here
}
//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
My HTML file just has a simple form with an input box and a button that when clicked calls the getTicker function. For some reason the chart is not being created and the AJAX call doesnt seem to work.
Is this something with HighStocks maybe? Any suggestions would be appreciated.
UPDATE Thank you for the suggestions, I have attempted to use JSONP but the chart still does not load. Can anybody see what I am doing wrong?
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Jeffrey Blake and Pawel Fus for your suggestions. Using JSONP I was able to get my program functioning correctly :)