0

In Wordpress, I'm trying to code a calendar with Ajax to refresh when changing month. My problem : i can only change month once, after that, seems like nothing happens when I click the link to change month.

You can see it here : https://www.bons-plans-voyage-new-york.com/backend/calendrier/

My code :

function calendar_enqueue_scripts()
{
    if(!is_admin())
    {
        if(is_home() || is_page("calendrier"))
        {
            wp_deregister_script('jquery');
            wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js', array(), null, true);
            wp_enqueue_script('calendrier', get_template_directory_uri().'/js/calendrier.js', array('jquery') );


            wp_localize_script('calendrier', 'ajax_object', array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce('my_nonce')
            ));

        }
    }
}
add_action('wp_enqueue_scripts', 'calendar_enqueue_scripts');


function my_action()
{
    if ( isset( $_POST['year']) &&  isset($_POST['month'])  )
    {
        check_ajax_referer( 'my_nonce', 'nonce' );  // This function will die if nonce is not correct.
        $calendrier = get_html_calendar($_POST['year'],$_POST['month']);
        echo $calendrier;
        exit();
    } 
}
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );



function get_html_calendar($year = '',$month = '')
{
    // some stuff to generate calendar for given month & year

    $output = '';
    $output .= '<div id="calender_section" class="cf">';
    $output .= '<h2>';
    $output .= '<a year="'.date("Y",strtotime($date.' - 1 Month')).'" month="'.date("m",strtotime($date.' - 1 Month')).'">&lt;&lt;</a>';
    $output .= '<select name="month_dropdown" class="month_dropdown dropdown">'.getAllMonths($dateMonth).'</select>';
    $output .= '<select name="year_dropdown" class="year_dropdown dropdown">'.getYearList($dateYear).'</select>';
    $output .= '<a year="'.date("Y",strtotime($date.' + 1 Month')).'" month="'.date("m",strtotime($date.' + 1 Month')).'">&gt;&gt;</a>';
    $output .= '</h2>';

    // ... etc
    return $output;
}

And my calendrier.js :

(function($)
{   
    function ajax_refreshCalendar(target_div, year, month)
    {
        $.ajax({
            url : ajax_object.ajax_url, // Note that 'ajax_object' is from the wp_localize_script() call.
            type : 'post',
            data :
            {
                action : 'my_action',  // Note that this is part of the add_action() call.
                nonce : ajax_object.nonce,  // Note that 'aj_demo_nonce' is from the wp_localize_script() call.
                year : year,
                month : month,
            },
            success : function( response )
            {
                console.log("success");
                console.log(response);
                $("#"+target_div).html(response);
            }
        }).fail(function (response)
        {
            // This stuff only happens if things fail miserably.
            console.log("fail");
            console.log(response);
        });
    }

    $(document).ready(function()
    {
        // Detect clics
        $("#calender_section a").on('click', function(e)
        {
            console.log("clic");

            // Prevent them from actually visiting the URL when clicking.
            e.preventDefault();

            var year = $(this).attr('year');
            var month = $(this).attr('month');
            var target_div = 'calendrier_wrapper';

            ajax_refreshCalendar(target_div, year, month);
        });
    });
})(jQuery);

What am I missing ? ** edit : weirder, I got different results depending on wheter i'm logged in or not. I'm lost here.

0

Your event target (#calender_section a) is replaced after refreshing the calendar. Because of the replacing, the event listener isn't applied to the target anymore. You have to apply the event listener to a parent element which doesn't get replaced (here it is #calendrier_wrapper) and use the selector parameter of on (see http://api.jquery.com/on/):

$("#calendrier_wrapper").on('click', '#calender_section a', function(e) {
    ...
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.