简体   繁体   中英

Previous and next date using jquery (ajax) and php

I have some kind of calendar written in php with previous and next buttons. Now I want to use some ajax to go to the previous or next date without refreshing the page.

In the php file called by ajax I have a query which returns the tasks for a selected day (something like : ...WHERE date = $date ).

The problem is that I can't get to the day before today and so on, and to the day after today and so on.

Someone who can help?

EDIT

Buttons:

<button class='btn btn-default previous' data-date='$date'>
  <span class='glyphicon glyphicon-arrow-left' aria-hidden='true'></span>   
</button>
<button class='btn btn-default next' data-date='$date'>
  <span class='glyphicon glyphicon-arrow-right' aria-hidden='true'></span>
</button>

Jquery:

$(document).ready(function() {
    $('button.previous').click(function() {
        var date = $(this).data('date');
        $.ajax({
            type: "POST",
            data: { action : "previous" , date: date },
            url: "includes/ajax/plannerdata.php",               
            success: function(returnData){                    
                $("#planner-data").html(returnData);
            }
        });
    });
    $('button.next').click(function() {
    var date = $(this).data('date');
        $.ajax({
            type: "POST",
            data: { action: 'next', date: date },
            url: "includes/ajax/plannerdata.php",               
            success: function(returnData){                    
                $("#planner-data").html(returnData); 
            }
        });
    });
});

plannerdata.php:

switch ($_POST['action']) {
    case 'next':
        $date = strftime('%Y-%m-%d', strtotime($_POST['date'] .' -1 day'));
        break;
    case 'previous':
        $date = strftime('%Y-%m-%d', strtotime($_POST['date'] .' +1 day'));
        break;
}

And then I use $date in my query.

UPDATED plannerdata.php:

if (!isset ($_POST['date'])) { // At first page load or refresh (without using the previous/next buttons), plannerdata.php is also loaded bij ajax and injected in index.php
    $currentDatetime = new DateTime('NOW');
}
else { // Previous or next button is pressed
    $currentDatetime = new DateTime($_POST['date']);
}

    $dateModification = $_POST['action'];

    switch ($dateModification) {
        case 'previous':
            $currentDatetime->modify('-1 day');
            break;
        case 'next':
            $currentDatetime->modify('+1 day');
            break;
    }
    $date = $currentDatetime->format('Y-m-d');

EDIT

plannerdata.php;

if (!isset ($_SESSION['date'])) {
    $_SESSION['date'] = new DateTime('NOW');
}

if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['date']->modify('+1 day');
            break;
    }
}

$date = $_SESSION['date']->format('Y-m-d');

buttons (inside index.php). I removed the data-date attribute:

<button class='btn btn-default previous'><span class='glyphicon glyphicon-arrow-left' aria-hidden='true'></span></button>
<button class='btn btn-default next'><span class='glyphicon glyphicon-arrow-right' aria-hidden='true'></span></button>

The buttons are inside an and between both buttons the selected date is shown.

<ul>
    <li>button previous</li>
    <li><span id="planner_date">selected date</span></li>
    <li>button next</li>
<ul>

I also changed the Jquery. I make a simultaneous ajax call.

$(document).ready(function() {
    $('button.previous').click(function() {
        $.when(
                $.post("includes/ajax/plannerdata.php", {action: 'previous'}, function(data) {
                    plannerData = data;
                }),
                $.post("includes/ajax/date.php", {action: 'previous'}, function(date) {
                    calendardate = date;
                })
        ).then(function() {
            $("#planner-data").html(plannerData);
            $("#planner_date").text(calendardate);
        });
    });
    $('button.next').click(function() {
        $.when(
                $.post("includes/ajax/plannerdata.php", {action: 'next'}, function(data) {
                    plannerData = data;
                }),
                $.post("includes/ajax/date.php", {action: 'next'}, function(date) {
                    calendardate = date;
                })
        ).then(function() {
            $("#planner-data").html(plannerData);
            $("#planner_date").text(calendardate);
        });
    });
});

Date.php for returning the current date:

if (!isset ($_SESSION['current_date'])) {
    $_SESSION['current_date'] = new DateTime('NOW');
}

if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['current_date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['current_date']->modify('+1 day');
            break;
    }
}

$date = $_SESSION['current_date']->format('Y-m-d');
echo $date;

EDIT 2015-03-05:

Jquery:

$(document).ready(function() {
    $('button.previous').click(function() {
        $.when(
            $.post("includes/ajax/date.php", 
                {action: 'previous'}, 
                function(date) {
                   dates = jQuery.parseJSON(date);
                   calendardate = dates.dutch;

                    $.post("includes/ajax/plannerdata.php", 
                        {date: dates.sql},
                        function(data) {
                            plannerData = data;
                        })
                    })
                    ).then(function(){
                $("#planner_date").text(calendardate);
                $("#planner-data").html(plannerData);
            });
        });
});

date.php

if (!isset ($_SESSION['current_date'])) {
    $_SESSION['current_date'] = new DateTime('NOW');
}
if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['current_date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['current_date']->modify('+1 day');
            break;
    }
}
$date_1 = $_SESSION['current_date']->format('Y-m-d');
$date_2 = $_SESSION['current_date']->format('d-m-Y');
$response = array('sql' => $date_1, 'dutch' => $date_2);
echo json_encode($response);

UPDATE 2015-03-08

$(document).ready(function() {
    $('button.previous').click(function() {
        var calendardate;
        var plannerData;
        $.when(
            $.post("includes/ajax/date.php", 
                {action: 'previous'}, 
                function(date) {
                   dates = jQuery.parseJSON(date)
                   calendardate = dates.dutch;

                    $.post("includes/ajax/plannerdata.php", 
                            {date: dates.sql},
                            function(data) {
                               plannerData = data;
                            })}
                        )).then(function(){
                $("#planner_date").text(calendardate)
                $("#planner-data").html(plannerData);
            });
        });
});

As i can see, best for you should be using PHP DateTime . You can modify your script to something like this:

$dateModification=$_POST['action'];//for clarification
//Datetime understands every format strtotime does
$currentDatetime=new DateTime($_POST['date']);

switch ($dateModification) {
    case 'next':
        $currentDateTime->modify("+1 day");//simple, isn't it?
        break;
    case 'previous':
        $currentDateTime->modify("-1 day");
        break;
}
//final result
$date=$currentDateTime->format("Y-m-d");

With DateTime you can easily manipulate dates as objects. It's also possible to compare two Datetime objects with < > == signs as easy as:

$firstDatetime=new Datetime("2015-02-20");
$secondDatetime=new Datetime("2015-02-25");
if ($firstDatetime<$secondDatetime)
{
    echo '$firstDatetime was indeed first!';
}

Try it out yourself :)

EDIT - How to handle date modifications on server side:

Few more thoughts about it. Your updated code is making two AJAX calls to server, both of them are modifying datetime object. As it would work, it's duplicating code. Let's try to modify calls and script to work on just one DateTime object. Let's move date modification to your date.php and plannerdata.php will be working on same date variable.

Javascript:

$(document).ready(function() {
    $('button.previous').click(function() {
        $.post("includes/ajax/date.php", 
            {action: 'previous'}, 
            function(date) {
                dates = jQuery.parseJSON(date)
                $("#planner_date").text(dates.dutch)
                $.post("includes/ajax/plannerdata.php", 
                    {date: dates.sql},
                    function(data) {
                        $("#planner-data").html(data);
                    })
            })
    })
});

PHP:

Date.php will remain the same, we must change just plannerdata.php to use same variable:

//we remove that block, as it will be set in date.php
/*if (!isset ($_SESSION['date'])) {
    $_SESSION['date'] = new DateTime('NOW');
}

if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['date']->modify('+1 day');
            break;
    }
}*/

$date = $_SESSION['current_date']->format('Y-m-d');

That should be it! :)

How to create DateTime from specific format?:

For such purposes exist function DateTime::createFromFormat . Example usage:

setlocale(LC_TIME, "nl_NL");//firstly we need to setlocale, so month names will be properly recognized
$dateString='6 maart 2015';
$datetime=DateTime::createFromFormat("j F Y", $dateString);

This will return datetime object, which you can operate on.

Use INTERVAL, for example:

TOMORROW:

SELECT * FROM table WHERE date = $date + INTERVAL 1 DAY

YESTERDAY

SELECT * FROM table WHERE date = $date - INTERVAL 1 DAY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM