Requirejs doesn't load jquery1.7 from CDN as module - php

I need to load jQuery1.7 as module, I've seen this code of #jrburke:
requirejs.config({
paths: {
'jquery' : 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min'
}
});
require(['jquery'], function($) {
//$ points to jQuery
});
It's not very useful for me, because all .js name are generated by server-side, I got them from php-array.
So, I wrote this:
require(['http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js'],
function($) {
//$ points to jQuery
});
But $ is null inside this function.
UPDATE:
Here is my php-template that render my js-scripts for this page:
<script src="http://requirejs.org/docs/release/1.0.1/minified/require.js">
</script>
<script>
require([
<?php echo "'". implode("',\n\t'", $this->scripts) . "'\n"; ?>
], function($){
console.warn ($); // null ;(
// loaded jQuery
window.$ = $;
// Load main client script for this page
boot( '<?php echo $this->eprint($this->content_page); ?>' );
});
</script>
and it is my php-array for this page (page index):
$scripts = array(
'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js',
'http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js',
'/js/libs/jquery.history.js?v=1321687090',
'/js/libs/coolclock.js?v=1321629683',
'/js/libs/excanvas.js?v=1321629683',
'/js/client.modules.js?v=1321703735',
'/js/client.all.js?v=1322512192',
'/js/boot.js?v=1322512037',
'/js/client.index.js?v=1321689884'
);

Have your php array of the form:
$jquery = array (
'jQuery' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js'
);
Then try:
requirejs.config({
paths: <?php echo json_encode($jquery) ?>
});
require(['jquery'], function($) {
//$ points to jQuery
});

Related

Including a github jquery plugin in Wordpress

I am trying to include a plugin from github (https://github.com/rendro/countdown) the right way on my wordpress site. After hours of research in the codex and here on stack I still cannot find a way to make it work.
If I use the default method:
1) Adding these lines to the <head> of my header.php file:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/path/to/jquery.countdown.js"></script>
2) Initializing the plugin with my desired configuration in between </head> and <body> in my header.php file, in this case:
<script>
$(function() {
var endDate = "November 30, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
</script>
3) And then calling the plugin in my html file:
<?php if(is_front_page() ) { ?>
<div id="cdtoevent" class="countcont">
<div class="countdown styled"></div>
</div>
<?php } ?>
It works perfectly !
If, however, I try doing it the right way
(If I understand well, wordpress ships with jQuery by default, by using the default method I'm making the user download jquery twice which augments my loading time as well, right ?)
Which means enqueuing jquery and then my script in my functions.php file like so:
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
And then repeat step 2) and 3) of the default method, it simply does not work ! I tried wrapping my jquery code in step 2) just like this:
jQuery(document).ready(function( $ ) {
// $ Works! You can test it with next line if you like
// console.log($);
});
But it still does not work.
If anybody could help, it would truly be greatly appreciated !
What I currently have in my header.php:
<?php if(is_front_page() ) { ?>
<div id="cdtoevent" class="countcont">
<div class="countdown styled"></div>
</div>
<?php } ?>
What I currently have in my footer.php:
<script type="text/javascript">
$(function() {
var endDate = "November 14, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
</script>
What I currently have in my functions.php :
// Loads JavaScript file with functionality specific to LCQC.
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
The jquery plugin (.js)
It's a good idea to use a function to enqueue your script. However: where do you call this function? You need to call it to enqueue your script. The best way to do this is by attach it to the right action (wp_enqueue_scripts): add_action('wp_enqueue_scripts', 'add_cdtoevent');.
I wrote a guide about including scripts in WordPress if you want more information about this function. It's useful to know how it works, as you can then discover that enqueuing jQuery manually is useless: you indicated that it's a dependency, so WordPress will automatically add it if needed.
I finally got it to work !
First, I had misplaced this as it was within another function in my functions.php file..
// Loads JavaScript file with functionality specific to LCQC.
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
Afterward, I made sure my script was declared this way (due to the noConflict() variable wordpress uses) right before my closing body tag:
<script type="text/javascript">
jQuery(document).ready(function($) {
$(function() {
var endDate = "November 14, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
});
</script>
And finally, I modified the following lines in jquery.countdown.js:
jQuery.fn.countdown = function(options) {
return $.each(this, function(i, el) {
var $el = $(el);
if (!$el.data(NAME)) {
// allow setting the date via the data-date attribute
if ($el.data(DATA_ATTR)) {
options.date = $el.data(DATA_ATTR);
}
$el.data(NAME, new Countdown(el, options));
}
});
};
to:
jQuery(document).ready(function($) {
jQuery.fn.countdown = function(options) {
return $.each(this, function(i, el) {
var $el = $(el);
if (!$el.data(NAME)) {
// allow setting the date via the data-date attribute
if ($el.data(DATA_ATTR)) {
options.date = $el.data(DATA_ATTR);
}
$el.data(NAME, new Countdown(el, options));
}
});
};
});
Thank you all for your help !

Reload/Update include PHP file in jquery on wordpress plugin

This issue is resolved. My friend helped me here is the working code:
<script type="text/javascript">
setInterval(jQuery.get("<?php
$url = plugin_dir_url( $file );
echo plugins_url( 'update.php' , __FILE__ ); ?>", function(responseData) {
jQuery("#cur_pos").html(responseData);
}), 1000 * 300);
</script>
<div id="cur_pos">
</div>
I want to reload a php file every so often to update a widget im making for wordpress.
My code thus for ive hacked together doesn't seem to work. it will work when i use the simple include but wont refresh of course. What am I missing?
<script type="Javascript">
// reload php
if(!jQuery && $) {
var jQuery = $;
}
function updatePos(){
UpdateInSeconds = 30;
jQuery('#cur_pos').load('<?php
$url = plugin_dir_url( $file );
echo plugins_url( 'update.php' , __FILE__ ); ?>');
setTimeout("updatePos();",UpdateInSeconds*1000) ;
}
jQuery(document).ready(function(){
updatePos();
});
</script>
<div id="cur_pos">
</div>
This is the output:
<script type="Javascript">
// reload php
if(!jQuery && $) {
var jQuery = $;
}
function updatePos(){
UpdateInSeconds = 30;
jQuery('#cur_pos').load('http://www.thepuzzycat.com/wp-content/plugins/ArduinoStats/update.php');
setTimeout("updatePos();",UpdateInSeconds*1000) ;
}
jQuery(document).ready(function(){
updatePos();
});
</script>
<div id="cur_pos">
</div>
setInterval(jQuery.get("http://www.thepuzzycat.com/wp-content/plugins/ArduinoStats/update.php", function(responseData) {
jQuery("#cur_pos").html(responseData);
}), 1000 * 300);
It's not the best solution for performance and other aspects, but it does work and it's better than using a recursive function.

how to call external php file in WordPress using ajax

I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I'm pretty new to WordPress.
I have solve my problem on my own.First i have define ajaxurl in my themes function.php like below:
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<? }
?>
And I put the below script on the top of my plugin file.
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
var data = {
action: 'my_action',
value: val,
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
and here's the field, for which i am trying to do in my plugin.
<textarea name="custom_text_message" id="custom_text_message"></textarea>
and then I put my action which i m calling to my script in function.php.
add_action('wp_ajax_my_action', 'my_action_session');
function my_action_session() {
global $wpdb; // this is how you get access to the database
session_start();
$_SESSION['cus_msg'] = $_POST['value'];
die(); // this is required to return a proper result
}
and then call my session value in to my function.That's all i do and work for me and i hope this will helps someone else.
Note:
The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action.
In WordPress, Ajax requests should be made to http://your-wordpress-site/wp-admin/admin-ajax.php - which can be obtained using admin_url( 'admin-ajax.php' ) - and you should use action parameter to specify which function to call. You can pass the admin-ajax path to your javascript file via localization.
Add to your plugin PHP file after you enqueue your script:
wp_localize_script( 'your-script', 'js_obj', array('ajax_url' => admin_url( 'admin-ajax.php' ) );
In your javascript:
jQuery.post(js_obj.ajax_url, {value: val, action: 'run-my-ajax'})
Function to process the ajax in your plugin PHP file:
function call_my_ajax(){
// do stuff
exit;
}
add_action('wp_ajax_run-my-ajax', 'call_my_ajax');
add_action('wp_ajax_nopriv_run-my-ajax', 'call_my_ajax');
Read more: https://codex.wordpress.org/AJAX_in_Plugins
<script type="text/javascript">
function setVal()
{
jQuery.ajax({url:"<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php",success:function(result){alert(result);}}
}
</script>
WordPress works on absolute paths, use a complete URL instead of the relative URL:
jQuery.post('session.php', {value: val})
Use something like:
jQuery.post('<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php', {value: val})

How to properly echo PHP variables within JS script?

I have this script that needs to print and it is within a PHP file as I need to pass it options because I am using the jQuery UI Tabs plugin.
Here is what I have:
<?php
$collapsible = "true";
$active = "2";
$options = array( 'collapsible' => $collapsible, 'active' => $active );
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : <?php echo $options["collapsible"]; ?>,
active : <?php echo $options["active"]; ?>
});
});
</script>
Ok so everything works however the two options collapsible and active isn't effecting it. But if I bypass the php variables and just hardcode the option settings in for collapsible and active, then it works. So I am not sure why the variables have no effect. I've even tried type casting it with (int) for active and (bool) for collapsible but still no dice.
Thanks for looking.
Rather than adding quotes, run the value through json_encode. This will ensure proper escaping as well:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : <?php echo json_encode($options["collapsible"]) ?>,
active : <?php echo json_encode($options["active"]) ?>'
});
});
</script>
It also gives you the added benefit of being able to use literal types as opposed to all strings in your PHP:
<?php
$collapsible = true;
$active = 2;
And, per axel.michel suggestion in comments, could be simplified to:
<?php
$options = array('collapsible' => true, 'active' => 2);
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs(<?php echo json_encode($options); ?>);
});
</script>
Try adding quotes around the values and encode the output
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : '<?php echo $options["collapsible"] ); ?>',
active : '<?php echo $options["active"] ); ?>'
});
});
</script>

Yii-bootstrap Tabs event handler

I'm using bootstap tabs, and Im trying to load the content via ajax rather than set it in PHP. My code:
<script type="text/javascript">
function test(e){
console.log(e.target);
//load ajax stuff here
}
</script>
<?php
$this->widget('bootstrap.widgets.TbTabs', array(
'type'=>'tabs',
'placement'=>'above', // 'above', 'right', 'below' or 'left'
'tabs'=>array(
array('label'=>'Ogólne', 'content'=>'Czekaj...', 'active'=>true),
array('label'=>'Książka adresów', 'content'=>'Czekaj...'),
array('label'=>'Cośtam', 'content'=>'Czekaj...'),
),
'events'=>array('shown'=>'test')
)); ?>
However I keep getting this error:
Uncaught TypeError: Object test has no method 'apply'. I tried creating an object, but it still didn't work. Any ideas?
A little clarification, JS code created by the framework:
<script type="text/javascript">
/*<![CDATA[*/
jQuery(function($) {
jQuery('a[rel="tooltip"]').tooltip();
jQuery('a[rel="popover"]').popover();
jQuery('#yw0').tab('show');
jQuery('#yw0').on('shown', 'test');
jQuery('#collapse_0').collapse({'parent':false,'toggle':false});
});
/*]]>*/
</script>
This should work
Javascript:
<script type="text/javascript">
var test = function(e) {
console.log(e.target);
//load ajax stuff here
}
</script>
TbTabs events ( prefixed with 'js:' )
<?php
...
'events'=>array('shown'=>'js:test'),
....
?>

Categories