I am displaying events with a date filter in wordpress. Current date is preselected and so events on the current day display by default. If someone clicks on another date, I call function newDate.
Problem: I pass the new variable with post method successfully, but can't pass it to php. Variable is in the unix timestamp format.
//calendar.js
function newDate(selectedDate){
var sendDate = selectedDate;
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate : sendDate
}
});
}
In my functions php I enqueue, localize the scrip and call the functions
//functions.php
wp_enqueue_script( 'calendar', get_template_directory_uri() .
'/resources/js/calendar.js', array( 'jquery' ), '1.0', true);
wp_localize_script('calendar', 'ajax_date', array(
'ajaxurl' => admin_url('admin-ajax.php'));
add_action( 'wp_ajax_nopriv_submit_date', 'submit_date' );
add_action( 'wp_ajax_submit_date', 'submit_date' );
function submit_date(){
$newdate = $_POST['sendDate'];
wp_die();
};
And finally my php file for displaying events. var_dump prints out null and echo also displays no content.
<div id ="events-container">
<?php
echo $newdate;
var_dump($newDate);
?>
EDIT - FIXED Thank you, it worked, my code as follows:
//events-page.php
<div id ="events-container">
<?php
echo get_events($args);
?>
</div>
//calendar.js
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate1 : date1,
sendDate2 : date2
}
}).done(function(data) {
console.log( data ); // will log the data you get back from your PHP function.
// Now you can display it on the view
$('#events-container').html(data);
})
//functions.php
wp_enqueue_script( 'calendar', get_template_directory_uri() . '/resources/js/calendar.js', array( 'jquery' ), '1.0', true);
wp_localize_script('calendar', 'ajax_date', array(
'ajaxurl' => admin_url('admin-ajax.php')));
//ajax actions
add_action( 'wp_ajax_nopriv_submit_date', 'submit_date' );
add_action( 'wp_ajax_submit_date', 'submit_date' );
function submit_date(){
$newdate1 = $_POST['sendDate1'];
$newdate2 = $_POST['sendDate2'];
$args = array(
'post_type' => 'epsa_events',
'posts_per_page' => 5,
'order' => 'ASC',
'meta_query' => array (
array(
'key' => 'start_time',
'value' => array($newdate1, $newdate2),
'compare' => 'BETWEEN'
)
));
get_events($args);
wp_die();
};
function get_events($args){
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="entry-content">';
the_title();
the_content();
$startTime = DateTime::createFromFormat('Y-m-d H:i', get_field('start_time'));
echo date_format($startTime, 'H:i a d.m.');
echo '</div>';
endwhile;
}