cookie cookie - 4 months ago 29
Javascript Question

jQuery date picker with PHP example

I'm trying to send some data to the server asynchronously like thus:

(function($){
$(document).ready(function($){

var hiddenElement = $("#datepicker");

$("#date_search").on('click', function(e){
e.preventDefault();

if(hiddenElement.is(':visible')){
hiddenElement.datepicker().slideUp(700);

} else {
hiddenElement.datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selectedDate = $(this).val();

var request = $.ajax({
url: "",
method: "GET",
data: {date: selectedDate},
dataType: "html"
});

request.done(function(msg){

});
}
}).slideDown(700);
}
})

});
})(jQuery)


<?php // front-page.php
$filter_date = isset($_REQUEST['date']) ? $_REQUEST['date'] : current_time('Y-m-d');

print_r( $filter_date );
?>

<style>
html, body, #page, #content {height: 100%;}
#datepicker {display:none;}
#searchby {list-style-type: none;}
#searchby li {float: left;padding-right: 1em;}
</style>


<ul id="searchby">
<li><a id="date_search" href="">search by date</a><div id="datepicker"></div></li>
<li><a href="">search by category</a></li>
<li><a href="">archive</a></li>
</ul>


Clicking on any date within the datepicker and the PHP script prints '2016-07-29' i.e. todays date to the screen. Not what I'm looking for. It should be printing a users selection of course.

Looking at the console I can see:

enter image description here

But could use a push to get it working.

Answer

First off, your jQuery should be rewritten as:

var request = $.ajax({
    url: "",
    method: "GET",
    data: {date: selectedDate},
    dataType: "html",
    success: function(res) {
            console.log(res);
            //Do what you want here with the date
        }
});

Also: Because you're calling the script itself, you're going to get all the output (html, and other data). Usually, you only want JSON or a string of exactly what you need. You can do this in one of 2 ways.

Call another script that does nothing but get the date, and return a string. ex. getdate.php, which has only:

 print_r( $filter_date ); 
?>

Or exit the script if date is set in $_REQUEST:

<?php // front-page.php
 if ( isset($_REQUEST['date']) )
 {
      echo $_REQUEST['date'];
      exit;
 }
?>