Move through PHP calendar months with jQuery AJAX
I am creating an events calendar in a WordPress theme using David Walsh's calendar function. I want to move between months with AJAX but am unfamiliar and having trouble posting and getting the month and year variables. I am referencing this AJAX video tutorial.
At the top of the page template, I have this function:
function swapContent(month,year) {
jQuery("#calendar").html("<img src='images/ajax-loader.gif'>").show();
var url="calendar.php";
jQuery.pos开发者_开发知识库t(url, {contentVar: month, year}, function(data){
jQuery("#calendar").html(data).show();
});
}
In calendar.php:
$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
$year = (int) ($_GET['year'] ? $_GET['year'] : date('Y'));
$contentVar = $_POST['month']['year'];
And my previous/next month controls look like this:
$previous_month_link = '<a href="?month='.($month != 1 ? $month - 1 : 12).'&year='.($month != 1 ? $year : $year - 1).'" class="control" onClick="return false" onmousedown="javascript: swapContent("month", "year")">Previous Month</a>';
All of my calendar.php file here: http://pastebin.com/R9zpA3yM
Thanks in advance, any help much appreciated.
It doesn't look like you're setting the month and year correctly. You're passing in "month" and "year" as strings and then not setting them as the right parameter names to pass into your PHP script. Try this:
function swapContent(monthVal,yearVal) {
jQuery("#calendar").html("<img src='images/ajax-loader.gif'>").show();
var url="calendar.php";
jQuery.post(url, {month: monthVal, year: yearVal}, function(data){
jQuery("#calendar").html(data).show();
});
return false;
}
Then in your PHP:
$monthVal = ($month != 1 ? $month - 1 : 12);
$yearVal = ($month != 1 ? $year : $year - 1);
$previous_month_link = '<a href="?month='.$monthVal.'&year='.$yearVal .'" class="control" onClick="swapContent("'.$monthVal.'","'.$yearVal.'");">Previous Month</a>';
Rather than use onmousedown
I would just have the function in the onclick
, just make sure it returns false at the end of the function which I've included.
I am not sure how month, year and contentVar are all being used in your PHP script, so the following is an assumption, but it looks like you would just need something along the lines of:
$month = (int) ($_POST['month'] ? $_POST['month']
: ($_GET['month'] ? $_GET['month']
: date('m')));
$year= (int) ($_POST['year'] ? $_POST['year']
: ($_GET['year'] ? $_GET['year']
: date('Y')));
And then use those variables accordingly to get your data?
精彩评论