1

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);
            });
        });
});
2
  • Please include the code. Otherwise it will be almost impossible to actually fix the problem(s). Commented Feb 26, 2015 at 16:54
  • Very good idea with using $.when ! :) Commented Mar 5, 2015 at 8:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

16 Comments

Sorry, it took a while.. I didn't know about DateTime() yet, so, thank you! Very nice, and easy in use. But I still have a problem... I can't get the data-date attribute in the next/previous buttons updated with the new date... So it stays like <button class='btn btn-default previous' data-date='2015-03-03'> <span class='glyphicon glyphicon-arrow-left' aria-hidden='true'></span> </button> You can see my updated plannerdata.php in my question ;)
I also can't access $_POST['date'] in my index.php. You can see my updated plannerdata.php in my question ;)
@JK87 - it should be achievable, but i need more info. Do i correctly assume, that your plannerdata.php returning some HTML which you're inserting into webpage? (we can try to get with it our new calculated date, or calculate it on JS side) Also - what does it mean that you can't access $_POST['date']? Your JS is, indeed doing POST to it.
@JK87 - i suggested one modification to your actual code :) Remember to change also jquery handling for next-button (i attached example for previous)
@JK87 - I assume, that' something with variables being not set on time. As our code get a little complicate - i simplified it. See my updated answer
|
0

Use INTERVAL, for example:

TOMORROW:

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

YESTERDAY

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.