0

I have a function which specifies date depending on a variable

ex. $modification = "+1 Week"

function calendar($modification){

    $month = array("Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December");
    $date = new DateTime(date('Y-m-d'));
    $date->modify($modification);
    $year = $date->format('o');
    $week = $date->format('W');
    $fulldate = $date->format('c');
    $valEnc = 'W';
    $monthNum = $date->format('n');
    $modDate = date('Y-m-d',strtotime($fulldate));


    $mMon = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week")), date("Y") ));
    $mTue = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+1, date("Y") ));
    $mWed = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+2, date("Y") ));
    $mThu = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+3, date("Y") ));
    $mFri = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+4, date("Y") ));
    $mSat = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+5, date("Y") ));
    $mSun = date('n', mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+6, date("Y") ));
    $dayMonth = compact("mMon","mTue","mWed","mThu","mFri","mSat","mSun");

    $mon = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week")), date("Y")));
    $tue = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+1, date("Y")));
    $wed = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+2, date("Y")));
    $thu = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+3, date("Y")));
    $fri = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+4, date("Y")));
    $sat = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+5, date("Y")));
    $sun = date('j',mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+6, date("Y")));
    $days = compact("mon","tue","wed","thu","fri","sat","sun");
    $weekNum = date("W", strtotime("$year$valEnc$week"));

    $mName = $month[($monthNum)-1];
    $yearNum= $date->format('Y');


    $calendar= compact("dayMonth", "days", "weekNum", "mName", "yearNum");   // $calendar['array'][value] / $calendar[value]

    //print_r($calendar);
    return $calendar;
}

How can I specify $modification from buttons on a page and then reload the function?

Ex. Button to Increase = +1 week and Button to decrease = -1 week.

EDIT: SOLVED

PHP:

$dMod = $_GET['mod'];

$mod = $dMod;


if ($dMod >= 0) {
    $mod = '+'.$dMod.'';
}


$modification = "".$mod." week";
date_default_timezone_set ("/*TIMEZONE*/");

function calendar($modification){
    $todayweek = date('W', mktime(0, 0, 0, date('m'), date("d"), date("Y") ));
    $today = date('D');
    $month = array("Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December");
    $date = new DateTime(date('Y-m-d'));
    $date->modify($modification);
    $year = $date->format('o');
    $week = $date->format('W');
    if ($todayweek==$week && $today=='Fri'){
        $date->modify($modification);
        $year = $date->format('o');
        $week = $date->format('W');
    }

    $fulldate = $date->format('c');
    $valEnc = 'W';
    $monthNum = $date->format('n');
    $modDate = date('Y-m-d',strtotime($fulldate));


    $fMon = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week")), date("Y") );
    $fTue = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+1, date("Y") );
    $fWed = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+2, date("Y") );
    $fThu = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+3, date("Y") );
    $fFri = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+4, date("Y") );
    $fSat = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+5, date("Y") );
    $fSun = mktime(0, 0, 0, date('m', strtotime("$modDate")), date("d", strtotime("$year$valEnc$week"))+6, date("Y") );
    $fulldate = compact("fMon","fTue","fWed","fThu","fFri","fSat","fSun");

    $mMon = date('n', $fMon);
    $mTue = date('n', $fTue);
    $mWed = date('n', $fWed);
    $mThu = date('n', $fThu);
    $mFri = date('n', $fFri);
    $mSat = date('n', $fSat);
    $mSun = date('n', $fSun);
    $dayMonth = compact("mMon","mTue","mWed","mThu","mFri","mSat","mSun");

    $mon = date('j', $fMon);
    $tue = date('j', $fTue);
    $wed = date('j', $fWed);
    $thu = date('j', $fThu);
    $fri = date('j', $fFri);
    $sat = date('j', $fSat);
    $sun = date('j', $fSun);
    $days = compact("mon","tue","wed","thu","fri","sat","sun");

    $weekNum = date("W", strtotime("$year$valEnc$week"));

    $mName = $month[($monthNum)-1];
    $yearNum= $date->format('Y');


    $calendar= compact("fulldate", "dayMonth", "days", "weekNum", "mName", "yearNum");   // $calendar['array'][value] / $calendar[value]
    return $calendar;


}

?>

JS:

$( document ).ready(function() {


var $input = $('#calMod');


        var calCheckWeek = function() {

            var theDate = new Date();
                if(theDate.getDay() >= 5){        //if its friday, switch to next week
                    if ($calMod == 0);{
                       $input.val(1);
                    };
                };
        };

calCheckWeek();

var $calMod = $input.val();




$('.load-div').load('/inc/calendar.php?mod=' + $calMod, function () {

    if ($calMod <= 0) {
        $('.calendar-prev-week').hide();
    }

    else {
        $('.calendar-prev-week').show();
    }

    console.log("Calendar loaded successfully!");


    });


    $('.calendar-prev-week').click(function () {


        var $input = $('#calMod');
        var value = parseInt($input.val());

        value = value - 1;


        $input.val(value);
        var $calMod = $input.val();

        if ($calMod <= 0) {
            $('.calendar-prev-week').hide();
        }

        else {
            $('.calendar-prev-week').show();
        }


        $('.load-div').load('/inc/calendar.php?mod=' + $calMod, function () {


            console.log("Decreased Week Number");
        });
    });



 $('.calendar-next-week').click(function () {

        var $input = $('#calMod');

        var value = parseInt($input.val());

        value = value + 1;

        $input.val(value);
        var $calMod = $input.val();

        if ($calMod <= 0) {
            $('.calendar-prev-week').hide();
        }

        else {
            $('.calendar-prev-week').show();
        }


        $('.load-div').load('/inc/calendar.php?mod=' + $calMod, function () {

            console.log("Increased Week Number");

        });
    });

I created 2 buttons Increase & Decrease week, made a hidden input '#calMod', since the whole page does not get refreshed (i only load the calendar in a specific div '.load-div') the value will not be reset every time i press a button to increase or decrease week and since i only want it to show weekdays i added a check to see if its friday more more (if(theDate.getDay() >= 5), if it is it will change to next week when first loaded, you are still able to go back one week (to the current week) but not further back.

Now my "Week" calendar works as intended.

Next step is to select days and store them in JSon.. Thanks for the help and ideas!

  • First thought is a couple buttons with click handlers. But need more info to specify, like what do you do with the new date? – bloodyKnuckles Apr 08 '15 at 11:40
  • I print values from the function into a calendar div, thats why i want to refresh it, it shows one week at a time. – Plainawesomeweb Apr 08 '15 at 11:46
  • I got two buttons but i dont want to refresh the whole page when they are clicked, i just want them to change the variable and reload the function. – Plainawesomeweb Apr 08 '15 at 12:06

1 Answers1

1

Using an HTML button element to call a PHP function without a page reload:

calendar.html

<div id="buttons_week">
  <button>+1 Week</button>
  <button>-1 Week</button>
</div>
<div id="calendar"></div>

<script>

// get display target
var calendar = document.getElementById('calendar');

// get buttons and loop
Array.prototype.forEach.call(document.querySelectorAll('#buttons_week button'), function (elem) {

    // add function to click event
    elem.addEventListener('click', function (evt) {
        // set up XHR object
        if ( window.XMLHttpRequest ) {
            xmlhttp=new XMLHttpRequest() // IE7+, Firefox, Chrome, Opera, Safari
        }
        else { // IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {

// here's where you handle the response you get from the PHP script

                // for debugging
                //calendar.innerHTML = xmlhttp.responseText
                //console.log(JSON.parse(xmlhttp.responseText))

                // parse JSON string from server and update calendar
                var calendar_obj = JSON.parse(xmlhttp.responseText)
                calendar.innerHTML = calendar_obj.weekNum + '/' + calendar_obj.mName + '/' + calendar_obj.yearNum

            }
        }
        xmlhttp.open("GET","calendar.php?mod="+encodeURIComponent(evt.target.innerHTML),true);
        xmlhttp.send();
    })
})

</script>

calendar.php

<?php

echo json_encode(calendar($_GET['mod']));

function calendar($modification){
  // function body here, removed for brevity
}

?>

If you don't need to go to the server for something else, then here's an all JavaScript version. No need to call the server!

JSFiddle

<div id="buttons_week">
  <button>+1 Week</button>
  <button>-1 Week</button>
</div>
<div id="calendar"></div>

<script>

var calendar = document.getElementById('calendar');
Array.prototype.forEach.call(document.querySelectorAll('#buttons_week button'), function (elem) {
    elem.addEventListener('click', function (evt) {
        var calendar_obj = week_increment(evt.target.innerHTML)
        console.log(calendar_obj.days)
        console.log(calendar_obj.dayMonth)
        calendar.innerHTML = 
            calendar_obj.weekNum + '/' +
            calendar_obj.mName + '/' +
            calendar_obj.yearNum
    })
})

function week_increment(mod) {
    var dd = new Date()
    var week_inc = 7 * 24 * 60 * 60 * 1000
    if ( 0 === mod.indexOf('-') ) { week_inc *= -1 } // decrement week
    dd = new Date(dd.getTime() + week_inc)
    dd.setHours(0,0,0);

    var dayMonth = [], days = [], weekNum
    dd.setHours(-24 * ((dd.getDay() || 7) - 1))
    for ( ii = 0; ii < 7; dd.setHours(24), ii++ ) {
        days.push(dd.getDate())
        dayMonth.push(dd.getMonth()+1)
        if ( 3 === ii ) { // get weekNum on Thursday ??
            weekNum = Math.ceil((((dd-new Date(dd.getFullYear(),0,1))/8.64e7)+1)/7) // http://stackoverflow.com/a/18005464/2743458
        }
    }

    return { 
        'dayMonth': dayMonth,
        'days':     days,
        'weekNum':  weekNum, 
        'mName':    months[dd.getMonth()], 
        'yearNum':  dd.getFullYear()
    }
}

var months = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];

</script>
bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
  • This looks promising but the buttons only increase/decrease the week by 1 and never go back to 0, i want them to increase/decrease by 1 everytime i press it ($oldmodification + $newmodification = $modificaiton) thanks for your help! – Plainawesomeweb Apr 09 '15 at 07:29
  • @Plainawesomeweb The increment function you provided doesn't account for a calendar state. It always starts with today. How do you propose to maintain a calendar state, and how does the increment function access that state? – bloodyKnuckles Apr 09 '15 at 13:58