I create a chart with chart.js in PHP which looks like this:
$chart = <<<ECHO
<script type="text/javascript">
var ctx = document.getElementById("myChart").getContext("2d");
Chart.types.Bar.extend({
name: "myChart",
initialize: function () {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
}
});
new Chart(ctx).myChart(data, {
scaleLabel : "<%= value + ' $' %>"
});
</script>
ECHO;
echo $chart;
This code works fine if I run it in Javascript but unfortunately I need to display it via PHP (I use a component in a CMS) which doesnt work. I get the following error:
Parse error: syntax error, unexpected '=', expecting '}' in process.php(1227) : eval()'d code on line 154
I narrowed the error down to the initialize: function() {...} line of code. But why does it cause problems within the PHP echo?
I'm not sure why you're having problems, I don't think you should be.
But I have a better answer for you, use buffers instead of heredocs (they're easier to work with anyway)
Google ob_start to learn how it works, they're super useful
ob_start()?>
<script type="text/javascript">
var ctx = document.getElementById("myChart").getContext("2d");
Chart.types.Bar.extend({
name: "myChart",
initialize: function () {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
}
});
new Chart(ctx).myChart(data, {
scaleLabel : "<%= value + ' $' %>"
});
</script>
<?php $chart = ob_get_clean();
echo $chart;
Related
I am trying it since last 6 hours and nothing seems to work for me. I want to add target="_blank" on click of a button inside Wordpress editor -TinyMce.
Here is what I did till now :
Ref : https://wordpress.stackexchange.com/questions/141344/add-button-in-tinymce-editor-to-insert-text
functions.php
add_action( 'init', 'droid_buttons' );
function droid_buttons() {
add_filter( "mce_external_plugins", "droid_add_buttons" );
add_filter( 'mce_buttons', 'droid_register_buttons' );
}
function droid_add_buttons( $plugin_array ) {
$plugin_array['droid'] = get_template_directory_uri() . '/js/text-button.js';
echo get_template_directory_uri();
return $plugin_array;
}
function droid_register_buttons( $buttons ) {
array_push( $buttons, 'droid_title'); // droid_title
return $buttons;
}
text-button.js
(function() {
tinymce.create('tinymce.plugins.Droid', {
init : function(editor, url) {
editor.addButton('droid_title', {
title : 'Droid Title',
cmd : 'droid_title',
image : ''
});
editor.addCommand('droid_title', function() {
var selected_text = editor.selection.getContent();
var element = "http://www.google.com";
var return_text = "";
return_text = '<a href="'+element+'" class="droid_title" target="_blank">' + selected_text + '</span>';
editor.execCommand('mceInsertContent', 0, return_text);
});
},
});
// Register plugin
tinymce.PluginManager.add( 'droid', tinymce.plugins.Droid );
})();
So after adding above code in my functions.php file and text-button.js file, it adds a button in wordpress editor to add target="_blank" in on top of inserted link in selected text.
when I am inserting an url after clicking insert/edit link in editor, its showing as it is :
But after clicking the button..the url is changing to www.google.com as given in code.
I tried to figure out exactly what should I give as my element variable in js file but not able to figure out.
I went through the solution given here :
WordPress hook / filter to process link inside a post
and here :
How to set target attribute in tinyMCE
but not able to figure out the issue. Any help would be really appreciable. Thanks so much in advance.
As per the documentation of the plugin you will need to add a callback function in the addButton event. In this call back you should be accomplish what you are wanted.
Update: Please make sure you have the correct path for the js file in the functions.php file. It seems that in my case it will be $plugin_array['droid'] = get_template_directory_uri() . '/assets/js/text-button.js'; You have missed assets directory may be?
Try like this:
(function() {
tinymce.create('tinymce.plugins.Droid', {
init : function(editor, url) {
editor.addButton('droid_title', {
title : 'Droid Title',
cmd : 'droid_title',
image : '',
onclick: function() {
var selected_text = editor.selection.getContent();
var element = "http://www.google.com";
var return_text = "";
return_text = '<a href="'+element+'" class="droid_title" target="_blank">' + selected_text + '</span>';
editor.insertContent(return_text);
}
});
Working example demo
i need a little help using the jquery countdown keith wood - jquery countdown plugin
I am creating several countdowns by retrieving data from mysql database (php ajax call) and putting it into a div:
in php (getdetails.php -> gets $mid and $time from mysql-database):
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount".$mid."\"><script> $('#timecount".$mid."').countdown({until: ".$time."}); </script></div></div>";
$mrow.="TimeCounter ends here";
in JS i set the innerHTML with the data i got:
var url="getDetails.php";
var what="getTimeData";
console.log("call getTimeData");
var p1 = $.post(url,{what:what,selId:selValue,conName:"GId"});
p1.done(function(data){
console.log("Data -> : "+ data);
document.getElementById("CounterDiv").innerHTML=data
});
console.log(data) shows me the set html:
<div id="RowDiv" ><div id="timecount2"><script> $('#timecount2').countdown({until: 1454713200}); </script></div></div>
I get no errors but i dont see the counter... I do see the surrounding TimeCounter inserted here: TimeCounter ends here on the page. I suppose it is a client / server side issue. Maybe i need to call the function again after setting the innerHTML with the data. But i dont know how.
How can i solve this? Any ideas?
Instead of adding an inline script within your HTML element, you can initiate the counter within your callback/success function of jQuery.post(). In order to do this, you will have to change your PHP and JS like below:
PHP
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount" . $mid . "\" data-time=\"" . $time . "\"></div></div>";
$mrow.="TimeCounter ends here";
JS
var url = "getDetails.php",
what = "getTimeData";
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
$('#CounterDiv').html(data).find('[id^="timecount"]').countdown({until: $(this).data('time')*1});
});
UPDATE:
I don't know the plugin, but the scope of this might get changed when .countdown() is called. In such a case, you can use .each() function of jQuery to pass the element. Here is how you do that:
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
var $counters = $('#CounterDiv').html(data).find('[id^="timecount"]'),
$el,t;
$counters.each(function(index,element){
$el = $(element);
t = $el.data('time')*1;
$el.countdown({until: t});
});
});
Haven't tested the code but the point of my suggestion would be to avoid sending HTML in response and make getdetails.php respond with $mid and $time like:
$data = array(
'mid' => $mid,
'time' => $time
);
$response = json_encode($data);
Your JS code should look something like:
var url = "getDetails.php";
var what = "getTimeData";
console.log("call getTimeData");
$.post(url, {what: what, selId: selValue, conName: "GId"}, function (data) {
console.log("Data -> : " + data);
var id = 'timecount' + data.mid;
var row = '<div id="RowDiv"><div id="' + id + '"></div</div>';
$("#CounterDiv").html(row);
$('#' + id).countdown({until: data.time});
}, 'json');
I am trying to pass several variables from a php page into a java script. However only the first parameter is being passed.
The php page calls the script like this:
<?
$sdate = 0;
$edate = 2;
?>
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid('<? echo $sdate; ?>', '<? echo $edate; ?>');
};
</script><BR>
The Java Script being called is:
function DatabaseGrid(sdate, edate)
{
this.editableGrid = new EditableGrid("demo", {
enableSort: true,
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid(sdate);
this.fetchGrid(edate);
}
DatabaseGrid.prototype.fetchGrid = function(sdate, edate) {
// call a PHP script to get the data
alert("loaddata_dailyotp.php?o=" + sdate + "&e=" + edate + "");
this.editableGrid.loadXML("loaddata_dailyotp.php?o=" + sdate + "&e=" + edate + "");
};
DatabaseGrid.prototype.initializeGrid = function(grid) {
grid.renderGrid("tablecontent", "testgrid");
};
I added the alert window to show the exactly what was being requested. I was expecting this:
loaddata_dailyotp.php?o=0&e=2
However what I am getting is:
loaddata_dailyotp.php?o=0&e=undefined
Why is my second parameter not going through?
You are not passing the "edate" parameter to your fetchGrid() call. That's why it's displayed as "undefined". For some reason you're calling fetchGrid() two times instead.
You could do it the following way:
<script type="application/json">
var payload = <?= json_encode(array('sdate' => $sDate, 'edate' => $eDate)); ?>
</script>
and then call your script:
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid(payload.sdate, payload.edate);
};
</script>
Call fetchGrid like this
function DatabaseGrid(sdate, edate)
{
this.editableGrid = new EditableGrid("demo", {
enableSort: true,
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid(sdate, edate);
}
You missed to pass the second parameter.
I am sharepoint developer. I faced the same issue in one my application where i was passing two values and only first value was reaching the other end. even alert box was showing two values.
Issue was only last values was not reaching other end so CRAZY SOLUTION was to pass 3 parameters, 3rd being test param so my two params were reaching other end and 3rd param which was anyways useless was getting neglected automatically.
Suggestion in your case :
Please check with THREE parameters whether you are still getting only 1 param or
params ;)
I want to send an array generated in jQuery to a php file. I get stuck on this. I tried several way but no luck. I want to echo/print_r the array in php file. Experts give me your kind look. My code is given below :
js:
<script>
jQuery(document).ready(function($){
url = '<?php echo includes_url().'cs_cause.php'; ?>';
var allVals = [];
$('#deleteProduct').click(function(){
$('.delete-product:checked').each(function() {
allVals.push($(this).val());
});
$.post(url,{ array : allVals }, function(response,status){
alert( response+ ' ' + status);
});
})
})
</script>
php :
<?php
if($_POST['array'])
{
$r = $_POST["array"];
print_r($r);
}
?>
Try something like this mate.
<script>
jQuery(document).ready(function($){
url = "http://localhost/fundraise/wp-content/themes/aidreform/include/cs_cause.php";
var allVals = [];
$('#deleteProduct').click(function(){
$('.delete-product:checked').each(function() {
allVals.push($(this).val());
});
$.post(url,{ array : allVals }, function(response,status){
alert( response+ ' ' + status);
});
})
})
</script>
Incase u move this file to the server change the url to
url = "/wp-content/themes/aidreform/include/cs_cause.php";
This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/