Loading text in tinyMCE for Wordpress via AJAX - php

I am using tinyMCE for Wordpress.
Which is the way to load text from server via AJAX?
Until now I have:
php:
<?php echo the_editor($_POST ? $_POST['content'] : '', $id = 'content'); ?>
javascript (which is failing...):
$("select[name='tpl']").live("change", function(e) {
var file = $(this).val();
var loadUrl = varsJs.WORDPRESS_PLUGIN_URL + "/templates/" + file;
$.get(loadUrl, function(result) {
$("#content").val(result);
});
});
The variable result is loaded with the desired text. No problem with that. But how pass this content to the tinyMCE?

if (typeof tinymce === "object"){
$("select[name='tpl']").live("change", function(e) {
var file = $(this).val();
var loadUrl = varsJs.WORDPRESS_PLUGIN_URL + "/templates/" + file;
$.get(loadUrl, function(result) {
tinymce.get("content").focus();
tinymce.activeEditor.setContent(result);
});
});
}
Note: varsJs is the second parameter of wp_localize_script function used to pass data from php to javascript. Really no needed in this precise issue but useful to know it.

Try this code, where 'content' is your field #ID
tinymce.init(tinyMCEPreInit.mceInit['content']);
this way and once tinymce is also loaded in current html,
you will reinit only one field, the one you received from Ajax Request.
also set this code before ajax saving Call
tinymce.activeEditor.save(); // get editor instance

Related

Jquery accordian within php, but call dynamic php script onclick

Here is the code I have currently,
<div class="panel">
<?php
if(isset($Uniid)) {
if (isset($from)) {
$url='Inevent.php';
include("display$category.php");
}
}
?>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName('panel');
for (var i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
var setClasses = !this.classList.contains('active');
setClass(acc, 'active', 'remove');
setClass(panel, 'show', 'remove');
if (setClasses) {
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
}
function setClass(els, className, fnName) {
for (var i = 0; i < els.length; i++) {
els[i].classList[fnName](className);
}
}
});
</script>
The main class which is the accordian is displayed currently, but when I click on the accordian, is when I want the panel to be executed, how do I go about doing it.
You can out your php code in a separate file and then call it with AJAX.
If you name your php file "loadPanel.php" then the AJAX request would look like this:
$.ajax({
url: "loadPanel.php"
}).done(function(response) {
$( '.panel' ).html( response );
});
Then add whatever php code you want inside you panel div to the loadPanel.php file.
The documentation for ajax is on the jQuery site here: http://api.jquery.com/jquery.ajax/.
There is a solution that isn't well known, but very powerful that consist in updating a part of the page with jQuery (works with the latest version of jQuery). So, to do that, you don't even have to create another page, so you just have to use the jQuery load() function.
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that you can use this method like this:
$( ".panel" ).load( window.location.href );

Jquery - Changing URL used in load()

I'm using the following to auto refresh the contents of a div.
$(document).ready(function() {
$("#log").load("test.php?q=" + $('#sq').val());
var refreshId = setInterval(function() {
$("#log").load("test.php?q=" + $('#sq').val());
}, 1000);
$.ajaxSetup({ cache: false });
});
This seems to work fine. I have a text field with the name 'sq' and anything entered in there is searched for by test.php.
My page also has 2 other form fields.
A checkbox and another text field. The checkbox has the id 'chk' and the text field 'txt'.
What I would like to do is change the URL being used by load() if the checkbox is ticked and a value is entered in the text field. Obviously this will also need to include 'sq'.
Can some one point me in the right direction.
The URL with out the check box being ticked is : ( is it is now )
test.php?q=VALUE_FROM_sq
With the checkbox ticked it needs to be :
test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq
Then test.php can use $_REQUEST to get the values passed.
My network box only supports php4 so that does limit me some..
Can some one point me in the right direction. Thanks
Just add some logic in the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
var refreshId = setInterval(LoadLog, 1000);
LoadLog();
});
function LoadLog() {
var sq = $('#sq').val();
var text = $("#txt").val();
var url = "test.php?q=" + encodeURIComponent(sq);
if ($("#chk").is(":checked") && text.length > 0)
url += "&s=1&txt=" + encodeURIComponent(text);
$("#log").load(url);
}
You could save the URL in a separate variable and update it on the changed event of the checkbox.
var url = "test.php?q=VALUE_FROM_sq"
$(document.body).on('change', '#chk', function (event) {
if ($(this).is(':checked')) {
url = "test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq"
} else {
url = "test.php?q=VALUE_FROM_sq"
}
}

calling on a complex function with onClick (ajax)

So I have this chunk of code here (below). It waits for a video to finish playing and then it looks up a cookie, sends that info to a php script through ajax, gets back a url from json, and reloads an iframe with a new url.
So I think you'll agree, it's sorta a lot going on.
Its purpose is to advance ONE forward in a playlist of videos. I am trying to create a button area where a user can click a >> sort of button and go forward. Which is exactly what this function does.
Rather than starting from scratch with a new function, is there a way to activate all of the above function functionality (ajax and all) when the user clicks that button?
<script>
function ready(player_id)
{
$f('play').addEvent('ready', function()
{
$f('play').addEvent('finish', onFinish);
});
function onFinish(play)
{
var now_video_var = $.cookie('now_video');
console.log ('player ' + now_video_var + ' has left the building');
var intermediate_integer = parseInt(now_video_var);
var request2 = $.ajax({
url : "geturl.php",
data : {intermediate_integer : intermediate_integer},
type : 'post'
}).done(function(data) {
var gotfrom = jQuery.parseJSON(data);
var NEWURL = gotfrom[1] ;
console.log(gotfrom);
console.log(data);
console.log(gotfrom[1]);
var theiframeforrealyo = document.getElementById('play');
$(theiframeforrealyo).attr("src", "http://player.vimeo.com/video/" + gotfrom[1] +"?api=1&player_id=play&title=0&byline=0&portrait=0&autoplay=1");
var new_video_var = intermediate_integer +1;
$.cookie('now_video', new_video_var);
console.log ( 'cookie function ok: the cookie is....');
console.log ($.cookie('now_video'));
});
}
}
window.addEventListener('load', function() {
//Attach the ready event to the iframe
$f(document.getElementById('play')).addEvent('ready', ready);
});
</script>

Display pdf blob with jquery ajax

This is my jQuery:
$( document ).ready(function() {
var instrID;
var cat;
$(window).load(function(){
});
$.post('ajax.php', {InstrumentID: instrID, catView: "pdf"}, function(data){
$('#displayPDF').append("<php> header('Content-type: application/pdf') </php>");
$('#displayPDF').append("<php> echo("+ data +") </php>");
});
This is my ajax or ajax.php:
<?php
include '../include/xxxxx.php';
$instrumentID = $_POST['InstrumentID'];
$category = $_POST['catView'];
$sql = "SELECT * FROM `xxxxx` WHERE `InstrumentID` = '" . $_POST['InstrumentID'] . "'";
$results = mysql_query($sql);
if($category == "pdf")
{
header("Content-type: application/pdf");
echo (mysql_result($results, 0, 'Instrument'));
}
?>
This is my div displayPDF It's empty:
<div id="displayPDF">
</div>
The jQuery and the div are in the same php file. I am wanting to display a pdf in the same page that the click event happens. Everything is working except for getting the pdf. When the pdf gets echoed to the div it just comes back as a bunch of characters. The pdf I am trying to display is less than 1 mb. Any ideas would be greatly appreciated.
Maybe this is not an answer to the specific question but, This question comes up at very first google search, so I would like to share my approach for downloading pdf when it's blob data.
$.ajax({
url: 'someurl',
method: 'get',
data: { param1: value1, param2: value2 },
xhr: function() {
const xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function (blob) {
const link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="my-pdf-file-name";
link.click();
}
});
You haven't set a value for instrID, also you're not sanitizing for input.
Anyway instead of using ajax you can just embed the pdf into the page
var source = 'ajax.php?InstrumentID='+encodeUriComponent(instrID)+'&catView=pdf';
$('#displayPDF').append('<object data="'+source+'" type="application/pdf">'+
'<embed src="'+source+'" type="application/pdf"/></object>');
and then use $_GET instead of post in your php.
I don't think you can display a PDF inline in this manner. Try switching to an iframe - that should work. That is set the location of the iframe to your ajax.php.

javascript based Jquery ajax function, unable to send post values

Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29

Categories