SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict AdRock952's Avatar
    Join Date
    Aug 2006
    Posts
    243
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Updating a php calendar with jquery using JSON. No putput

    I have a PHP calendar that I want to use Jquery ajax so I can click on the prev and next buttons to update the calendar dynamically.

    The php calendar works fine and I pass 2 variables to it for the month and the year.

    I have written the Jquery to try and use Ajax to get the calendar using JSON but it's not outputting anything to the screen.

    Because I need to pass back variables for the calendar next and prev buttons, I have used JSON.

    Here is an image of the output

    Untitled.png

    How can i get the calendar to display on the page and have i done the button correctly so it takes the variables from php and pass it back to the buttons?

    Here is my main page which will display the calendar and also my Jquery

    Code:
    <html>
    <head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
    	// <![CDATA[
    	
    	$(document).ready(function()
    	{
    		function loading_show()
    		{
    			$('#loading').html('<img src="images/loading.gif" alt="loading..." title="loading..>"/>').fadeIn('fast');
    		}
    		
    		function loading_hide()
    		{
    			$('#loading').fadeOut('fast');
    		}
    
    		function loadData(month, year)
    		{
    			loading_show(); 
                       
    			$.ajax({
    				type: "POST",
    				url: "cal2.php",
    				data: {month: month, year: year},
    				dataType: "json",
    				timeout: 5000,
    				success: function(json)
    				{
    					$(document).ajaxComplete(function(event, request, settings)
    					{
    	
    						console.log(json);
    						
    						for(var i = 0; i < json.length; i++)
    						{
    							var calmain = json[i].msg;
    							var cMonth = json[i].cMonth;
    							var cYear  = json[i].cYear;
    							var prev_year = json[i].prev_year;
    							var next_year = json[i].next_year;
    							var prev_month = json[i].prev_month;
    							var next_month = json[i].next_month;
    						}
    						
    						loading_hide();
    						
    						$("#curMonthYear").html(cMonth+" "+cYear);
    						$("#tblcalmain").html(calmain);
    						
    						afterLoad(prev_month, prev_year, next_month, next_year);
    					});
    				},
    				error: function(xhr, textStatus, errorThrown)
    				{
    				   alert('request failed');
    				}
    			});
    		}
    		
    		function afterLoad(prev_month, prev_year, next_month, next_year)
    		{
    			$('#cal-prev').on('click',function()
    			{
    				loadData(prev_month, prev_year);
    			});
    			
    			$('#cal-next').on('click',function()
    			{
    				loadData(next_month, next_year);
    			}); 
    		}
    		
    		loadData(9, 2013);  // For first time page load default results
    	});
    	
    	// ]]>
    </script>
    </head>
    <body>
    <div id="loading"></div>
    <div id="container">
    	<div id="calendarmain">
    		<table width="200">
    			<tr align="center">
    				<td align="center">
    					<table class="cal" width="100%" border="0" cellpadding="0" cellspacing="2">
    						<tr align="center">
    							<td colspan="7" class="blue">
    								<button class="left" type="button" id="cal-prev">&nbsp;</button>
    									<span id="curMonthYear"> </span>
    								<button class="right" type="button"  id="cal-next">&nbsp;</button>
    							</td>
    						</tr>
    						<tr>
    							<th>S</th>
    							<th>M</th>
    							<th>T</th>
    							<th>W</th>
    							<th>T</th>
    							<th>F</th>
    							<th>S</th>
    						</tr>
    					</table>
    					<table id="tblcalmain">
    					
    					</table>
    				</td>
    			</tr>
    		</table>
    		<noscript><p>Sorry, your browser does not support JavaScript!</p><p>You need JavaScript enabled to use this calendar.</p></noscript>
    	</div>
    </div>
    </body>
    </html>
    and this is the php calendar

    PHP Code:
    <?php
        header
    ('Content-type: application/json');
        
        
    date_default_timezone_set("Europe/London");
        
        
    $test = array();
        
        
    $monthNames = Array("January""February""March""April""May""June""July""August""September""October""November""December");
        if (!isset(
    $_GET["month"])) $_GET["month"] = date("n");
        if (!isset(
    $_GET["year"]))  $_GET["year"]  = date("Y");
        
        
    $cMonth $_GET["month"];
        
    $cYear  $_GET["year"];
                    
        
    $prev_year $cYear;
        
    $next_year $cYear;

         
    $prev_month $cMonth-1;
         
    $next_month $cMonth+1;

         if (
    $prev_month == ) {
        
    $prev_month 12;
        
    $prev_year $cYear 1;
      }
         if (
    $next_month == 13 ) {
        
    $next_month 1;
        
    $next_year $cYear 1;
      }

        
    $dateMonthYearArr = array();

        
    $timestamp mktime(0,0,0,$cMonth,1,$cYear);
        
    $maxday    date("t",$timestamp);
        
    $thismonth getdate ($timestamp);
        
    $startday  $thismonth['wday'];
        
        
    $msg ="";
        
        
    $newdate date('Y-m-d',$timestamp);
        
    $today date('Y-m-d');
        
    $newdate strtotime '-1 day' strtotime $newdate ) ) ;
        
    $newdate date('Y-m-d',$newdate);
        
        for (
    $i=0$i<($maxday+$startday); $i++) {
            if((
    $i 7) == $msg .= "<tr>\n";
            if(
    $i $startday$msg .= "<td></td>\n";
            else {
                
    $newdate strtotime '+1 day' strtotime $newdate ) ) ;
                
                
    $clickdate date 'd-M-Y' $newdate );
                
    $newdate date 'Y-m-d' $newdate );

                if(
    in_array($newdate$dateMonthYearArr)) {
                    
    $msg .= "<td class='callink' align='center' valign='middle'>";
                    if(
    $today == $newdate) {
                        
    $msg .= "<span class='bold'><a href='/coming-events/".$cickdate."'>".($i $startday 1) ."</a></span>";
                    }
                    else {
                        
    $msg .= "<a href='/coming-events/".$clickdate."'>".($i $startday 1) ."</a>";
                    }
                }
                else {
                    
    $msg .= "<td class='caldate' align='center' valign='middle'>";
                    if(
    $today == $newdate) {
                        
    $msg .= "<span class='bold'>".($i $startday 1)."</span>";
                    }
                    else {
                        
    $msg .= ($i $startday 1);
                    }
                }
                
    $msg .= "</td>\n";
            }
            if((
    $i 7) == $msg .= "</tr>\n";
        }

        
    $test['msg'] = $msg;
        
        
    $test['cMonth'] = $cMonth;
        
    $test['cYear'] = $cYear;
                    
        
    $test['prev_year'] = $prev_year;
        
    $test['next_year'] = $next_year;

         
    $test['prev_month'] = $prev_month;
         
    $test['next_month'] = $next_month;
        
        echo 
    json_encode($test);
    ?>

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,446
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Hi,

    There are a couple of things you need to change to get your script working:

    Code JavaScript:
    // Declare the prev/next variables once at the top of the script
    var prev_year,
        next_year,
        prev_month,
        next_month;
     
    function loading_show()
    {
        $('#loading').html('<img src="images/loading.gif" alt="loading..." title="loading..>"/>').fadeIn('fast');
    }
     
    function loading_hide()
    {
        $('#loading').fadeOut('fast');
    }
     
    function loadData(month, year)
    {
        loading_show(); 
     
        $.ajax({
            type: "POST",
            url: "cal2.php",
            data: {month: month, year: year},
            dataType: "json",
            timeout: 5000,
            success: function(json)
            {
                // No need to set an ajaxComplete function, as you're
                // already passing a success function to $.ajax
     
                // JSON result is a single object, not an array, so no
                // need to iterate over results, just assign prev/next
                // values to previous declared variables..
                prev_year = json.prev_year;
                next_year = json.next_year;
                prev_month = json.prev_month;
                next_month = json.next_month;
     
                loading_hide();
     
                // ..and pass cMonth/cYear/msg directly
                $("#curMonthYear").html(json.cMonth+" "+json.cYear);
                $("#tblcalmain").html(json.msg);
            },
            error: function(xhr, textStatus, errorThrown)
            {
               alert('request failed');
            }
        });
    }
     
    // Move click handlers outside of the success callback,
    // otherwise they get re-attached every time you make
    // an ajax request
    $('#cal-prev').on('click',function() {
        loadData(prev_month, prev_year);
    });
     
    $('#cal-next').on('click',function() {
        loadData(next_month, next_year);
    }); 
     
    loadData(9, 2013);
    I've added comments to show what I've changed and why, but let me know if anything's not clear.

    This will load the calendar for the current month, but the dates don't line up with the weekday headers properly, so I'd suggest that you also change your HTML slightly:
    HTML Code:
    <table class="cal" width="100%" border="0" cellpadding="0" cellspacing="2">
        <thead>
            <tr align="center">
                <td colspan="7" class="blue">
                    <button class="left" type="button" id="cal-prev"> &laquo; </button>
                        <span id="curMonthYear"> </span>
                    <button class="right" type="button"  id="cal-next"> &raquo; </button>
                </td>
            </tr>
            <tr>
                <th>S</th>
                <th>M</th>
                <th>T</th>
                <th>W</th>
                <th>T</th>
                <th>F</th>
                <th>S</th>
            </tr>
        </thead>
        <tbody id="tblcalmain"></tbody>
    </table>
    The last thing is that your prev/next buttons don't work, because your ajax request is submitting the year and month variables via POST, but your PHP script is checking $_GET, so you need to change one to make them consistant.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •