• Resolved darthmikeyd

    (@darthmikeyd)


    I am trying to convert a PHP/Javascript calendar app to a WordPress widget. I almost have it working, but when I try to move to either the next or previous month, I get the following error:

    TypeError: $ is undefined[Learn More] calendar.js:28:2
    getPrevmonth https://server/testfolder/directory/wp-content/plugins/calendar/calendar.js:28:2
    onclick https://server/testfolder/directory/:1:1

    This error points to the following code:

    	$.ajax({
            type: "GET", // use $_GET method to submit data
            url: 'processcalendar.php', // where to submit the data
            data: {
                newmonth : newmonth, // PHP: $_GET['newmonth']
                newyear  : newyear, // PHP: $_GET['newyear']
            },
            success:function(data) {
                $( '#calendardiv' ).html( data ); // add HTML results to empty div
                $( '#currentmonth' ).val( newmonth );
                $( '#currentyear' ).val( newyear );
            },
            error: function(errorThrown){
                $( '#calendardiv' ).html( '<p>Error retrieving data. Please try again.</p>' );
            }
        });

    What I think the problem is, is that I have to include the ajax libraries in the code, but I’ve tried a couple of different things, but can’t get it to work. Any advice is appreciated. As a note, I am new to developing for WordPress, and have never used AJAX or JQuery before. Here is the code:

    events.php

    <?php
    	/*
    		Plugin Name: Intranet Calendar Plugin Test
    		Description: Event Plugin
    		Version: 1.0.0
    		Author: Mike Dunham
    		License: GPLv2 or later
    		Text Domain: The Eagles Nest Web Design
    	*/			
    			
    	class Calendar_Widget extends WP_Widget {
    		
    		public function __construct() {
    			$widget_options = array( 
    		    	'classname' => 'calendar_widget',
    		      	'description' => 'This is an Event Widget',
    		    	);
    			parent::__construct( 'calendar_widget', 'Calendar Widget', $widget_options );
    		}
    
    		
    		public function widget( $args, $instance ) {
    		  	$title = apply_filters( 'widget_title', 'Calendar Test' );
    		  	echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title']; 
    		  	
    			wp_enqueue_style( 'calendar', plugins_url() . '/calendar/calendar.css',false,'1.1','all');
    			wp_enqueue_script('calendar', plugins_url() . '/calendar/calendar.js', array('jquery'), null, true);
    			
    			if (isset($_GET["newmonth"])) {
    				$month = $_GET["newmonth"];
    				$month = $month + 1;
    				$day = 1;
    				$year = $_GET["newyear"];
    				$newdate = mktime(0,0,0,$month,$day,$year);
    				$displaymonth = date("F", $newdate);
    				$displayyear = date("Y", $newdate);
    				$linkmonth = date("m", $newdate);
    				$linkyear = date("Y", $newdate);
    				$current = date("j");
    				$totaldays = date("t", $newdate);
    			} else {
    				$displaymonth = date("F");
    				$displayyear = date("Y");
    				$linkmonth = date("m");
    				$day = 1;
    				$linkyear = date("Y");
    				$current = date("j");
    				$totaldays = date("t");
    			}
    		?>
    			<div id="calendardiv">
    				<table id="calendar" border="1">
    					<tr>
    						<th id="prevmonth" valign="center"><button id="prev" class="button" onclick="getPrevmonth()"> < </button></th>
    						<th id="mainhead" colspan="5"><?php echo $displaymonth . " " . $displayyear; ?></th>
    						<th id="nextmonth" valign="center"><button id="next" class="button" onclick="getNextmonth()"> > </button></th>
    					</tr>
    					<tr>
    						<th id="header">Sun</th>
    						<th id="header">Mon</th>
    						<th id="header">Tue</th>
    						<th id="header">Wed</th>
    						<th id="header">Thu</th>
    						<th id="header">Fri</th>
    						<th id="header">Sat</th>
    					</tr>
    					<tr>
    						<?php
    						$first = date("w", mktime(0,0,0,$linkmonth,$day,$linkyear));
    						$ctr = 1;
    						$ctrcells = 0;
    						for ($i=0; $i<$first; $i++) {
    							echo "<td class='nil'></td>";
    						}
    						for ($i=$first; $i<=6; $i++) {
    							if ($ctr == $current) {
    								 echo "<td class='today'><a href='#'>$ctr</a></td>";
    							}else{
    								echo "<td class='day'><a href='#'>$ctr</a></td>";
    							}
    							$ctr++;
    						}
    						echo "</tr><tr>";
    						while ($ctr <= $totaldays) {
    							if ($ctr == $current) {
    								 echo "<td class='today'><a href='#'>$ctr</a></td>";
    							}else{
    								echo "<td class='day'><a href='#'>$ctr</a></td>";
    							}
    							$ctrcells++;
    							if ($ctrcells == 7) {
    								echo "</tr><tr>";
    								$ctrcells = 0;
    							}
    							$ctr++;
    						}
    						if ($ctrcells <> 0) {
    							for ($i=$ctrcells; $i<7; $i++) {
    								echo "<td class='nil'></td>";
    							}
    						}
    						
    						?>
    						
    					</tr>
    				</table>
    				<input type="hidden" name="currentmonth" id="currentmonth" />
    				<input type="hidden" name="currentyear" id="currentyear" />
    			</div>
    			
    		
    			<?php
    
    			echo $args['after_widget'];
    		}
    		
    		public function form( $instance ) {
    		  	$title = ! empty( $instance['title'] ) ? $instance['title'] : ''; 
    		  	?>
    		  	<p>
    		    	<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
    		    	<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
    		  	</p>
    		  	<?php 
    		}
    				
    		public function updatecalendar( $new_instance, $old_instance ) {
    		  	$instance = $old_instance;
    		  	$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
    		  	return $instance;
    		}
    		
    		
    		
    	}
    	
    	
    	function register_calendar_widget() { 
    		register_widget( 'Calendar_Widget' );
    	}
    	add_action('widgets_init', 'register_calendar_widget');
    
    	
    /************************************************************************************************************************************************************
     * This portion registers the activation, deactivation and uninstall hook
    /***********************************************************************************************************************************************************/
    	register_activation_hook( __FILE__, 'activate_calendar_plugin' );
    	//register_deactivation_hook( __FILE__, 'deactivate_staff_directory_plugin' );
    	register_uninstall_hook(__FILE__, 'uninstall_calendar_plugin');
    	
    /************************************************************************************************************************************************************
     * This portion creates the database tables when the plugin is activated
    /***********************************************************************************************************************************************************/
    	function activate_calendar_plugin() {
    		
    	}
    	
    /************************************************************************************************************************************************************
     * This portion deletes the database tables when the plugin is uninstalled
    /***********************************************************************************************************************************************************/
    	function uninstall_calendar_plugin() {
    		
    		
    	}
    
    /************************************************************************************************************************************************************
     * This portion Adds Menu Items for the plugin
    /***********************************************************************************************************************************************************/
    	function calendar_admin_menu_option() {
    		add_menu_page('Calendar Test', 'Calendar Test', 'manage_options', 'calendar_admin_menu', 'calendar_scripts_page', '', 200);
    	}
    	add_action('admin_menu', 'calendar_admin_menu_option');
    	
    /************************************************************************************************************************************************************
     * Main page for the events calendar plugin.
    /***********************************************************************************************************************************************************/
    	function calendar_scripts_page() {
    		global $wpdb;
    		
    		echo "<h2>Calendar Test Plugin</h2>";
    			
    			
    	}

    calendar.js

    function getPrevmonth() {
    			
    	var currentmonth = document.getElementById('currentmonth').value;
    	var currentyear = document.getElementById('currentyear').value;
    	
    	if (currentmonth) {
    		if (currentmonth == 0) {
    			var newmonth = 11;
    			var newyear = currentyear-1;
    		} else {
    			var newmonth = Number(currentmonth) - 1;
    			var newyear = currentyear;
    		}
    	} else {
    		var date = new Date();
    		var month = date.getMonth();
    		var year = date.getFullYear();
    		
    		if (month == 0) {
    			var newmonth = 11;
    			var newyear = year-1;
    		} else {
    			var newmonth = month - 1;
    			var newyear = year;
    		}
    	}
    	
    	$.ajax({
            type: "GET", // use $_GET method to submit data
            url: 'processcalendar.php', // where to submit the data
            data: {
                newmonth : newmonth, // PHP: $_GET['newmonth']
                newyear  : newyear, // PHP: $_GET['newyear']
            },
            success:function(data) {
                $( '#calendardiv' ).html( data ); // add HTML results to empty div
                $( '#currentmonth' ).val( newmonth );
                $( '#currentyear' ).val( newyear );
            },
            error: function(errorThrown){
                $( '#calendardiv' ).html( '<p>Error retrieving data. Please try again.</p>' );
            }
        });
    }
    
    function getNextmonth() {
    	
    	var currentmonth = document.getElementById('currentmonth').value;
    	var currentyear = document.getElementById('currentyear').value;
    	
    	if (currentmonth) {
    		if (currentmonth == 11) {
    			var newmonth = 0;
    			var newyear = Number(currentyear) + 1;
    		} else {
    			var newmonth = Number(currentmonth) + 1;
    			var newyear = currentyear;
    		}
    	} else {
    		var date = new Date();
    		var month = date.getMonth();
    		var year = date.getFullYear();
    		
    		if (month == 11) {
    			var newmonth = 0;
    			var newyear = year+1;
    		} else {
    			var newmonth = month + 1;
    			var newyear = year;
    		}
    	}
    	
    	$.ajax({
            type: "GET", // use $_GET method to submit data
            url: 'processcalendar.php', // where to submit the data
            data: {
                newmonth : newmonth, // PHP: $_GET['newmonth']
                newyear  : newyear, // PHP: $_GET['newyear']
            },
            success:function(data) {
                $( '#calendardiv' ).html( data ); // add HTML results to empty div
                $( '#currentmonth' ).val( newmonth );
                $( '#currentyear' ).val( newyear );
            },
            error: function(errorThrown){
                $( '#calendardiv' ).html( '<p>Error retrieving data. Please try again.</p>' );
            }
        });
    }

    processcalendar.php

    <?php
    	wp_enqueue_style( 'calendar', plugins_url() . '/calendar/calendar.css',false,'1.1','all');
    	wp_enqueue_script('calendar', plugins_url() . '/calendar/calendar.js', array('jquery'), null, true);
    	
    	if (isset($_GET["newmonth"])) {
    		$month = $_GET["newmonth"];
    		$month = $month + 1;
    		$day = 1;
    		$year = $_GET["newyear"];
    		$newdate = mktime(0,0,0,$month,$day,$year);
    		$displaymonth = date("F", $newdate);
    		$displayyear = date("Y", $newdate);
    		$linkmonth = date("m", $newdate);
    		$linkyear = date("Y", $newdate);
    		$current = date("j");
    		$totaldays = date("t", $newdate);
    	} else {
    		$displaymonth = date("F");
    		$displayyear = date("Y");
    		$linkmonth = date("m");
    		$day = 1;
    		$linkyear = date("Y");
    		$current = date("j");
    		$totaldays = date("t");
    	}
    ?>
    
    <table id="calendar" border="1">
    	<tr>
    		<th id="prevmonth" valign="center"><button id="prev" class="button" onclick="getPrevmonth()"> < </button></th>
    		<th id="mainhead" colspan="5"><?php echo $displaymonth . " " . $displayyear; ?></th>
    		<th id="nextmonth" valign="center"><button id="next" class="button" onclick="getNextmonth()"> > </button></th>
    	</tr>
    	<tr>
    		<th id="header">Sun</th>
    		<th id="header">Mon</th>
    		<th id="header">Tue</th>
    		<th id="header">Wed</th>
    		<th id="header">Thu</th>
    		<th id="header">Fri</th>
    		<th id="header">Sat</th>
    	</tr>
    	<tr>
    		<?php
    		$first = date("w", mktime(0,0,0,$linkmonth,$day,$linkyear));
    		$ctr = 1;
    		$ctrcells = 0;
    		for ($i=0; $i<$first; $i++) {
    			echo "<td class='nil'></td>";
    		}
    		for ($i=$first; $i<=6; $i++) {
    			if ($ctr == $current) {
    				 echo "<td class='today'><a href='#'>$ctr</a></td>";
    			}else{
    				echo "<td class='day'><a href='#'>$ctr</a></td>";
    			}
    			$ctr++;
    		}
    		echo "</tr><tr>";
    		while ($ctr <= $totaldays) {
    			if ($ctr == $current) {
    				 echo "<td class='today'><a href='#'>$ctr</a></td>";
    			}else{
    				echo "<td class='day'><a href='#'>$ctr</a></td>";
    			}
    			$ctrcells++;
    			if ($ctrcells == 7) {
    				echo "</tr><tr>";
    				$ctrcells = 0;
    			}
    			$ctr++;
    		}
    		if ($ctrcells <> 0) {
    			for ($i=$ctrcells; $i<7; $i++) {
    				echo "<td class='nil'></td>";
    			}
    		}
    		
    		?>
    		
    	</tr>
    </table>
    <input type="hidden" name="currentmonth" id="currentmonth" />
    <input type="hidden" name="currentyear" id="currentyear" />
    • This topic was modified 5 years, 10 months ago by darthmikeyd.
Viewing 4 replies - 1 through 4 (of 4 total)
  • $ is usually how people refer to jQuery. WordPress loads the jQuery library in no-conflict mode, so $ is not defined. Your plugin should enqueue your script with a dependency on jQuery (and you don’t need to load it yourself –be sure you aren’t), and be sure to wrap your code in a function that passes jQuery in as $. That will make it so you don’t have to change your code, but also keep from polluting the global namespace with your variables.

    Thread Starter darthmikeyd

    (@darthmikeyd)

    Thanks for the reply Joy. I believe I am enqueueing the code with

    wp_enqueue_script('calendar', plugins_url() . '/calendar/calendar.js', array('jquery'), null, true);

    Not to sound like a total idiot, but what the heck, that’s how I feel right now, how do I pass jQuery as $?

    You code it like this:

    ( function( $ ) {
      // all your code here
    } )( jQuery );
    Thread Starter darthmikeyd

    (@darthmikeyd)

    That did it!! Thanks for the response and help!!!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Convert PHP/Javascript app to WordPress plugin’ is closed to new replies.