Skip to content Skip to sidebar Skip to footer

Jquery Datepicker To Php Variable Without Form

I'm having a situation and I've got the feeling it's quite simple to fix, but I can't seem to find the right keywords / way to do it. What I've got A JQuery Datepicker without a fo

Solution 1:

Javascript UPDATED:

$("#datepicker").datepicker({
    onSelect: function() {
        var date = $('#datepicker').datepicker("getDate");
        $.ajax({
            url: "processdate.php",
            type: "POST",
            async: true,
            data: {
                selected_date: date
            },
            success: function(resp) {
                if (resp === "true") {
                    alert("it worked");
                } else {
                    alert("nope :-(");
                }
            } 
        });
    }
}).datepicker("setDate", newDate());//Set current date.

JAVASCRIPT NOTE

This will set the date to the current date, for display purposes only, but it will not run the AJAX call because if it did your users would be instantly redirected. Personally I recommend adding a button next to the datepicker that goes to the next page instead of automatically redirecting on select.

processdate.php, create this php file in same directory as page that has the js

<?php
session_start();
if(isset($_POST["selected_date"])){
    $_SESSION["date"] = $_POST["selected_date"];
    echo"true";
} else {
    echo"false";
}
?>

your php, this is the page you should redirect to after you have the AJAX working.

<?php
session_start();
$date = $_SESSION["date"];
$dirname = "images/$date/";
$images = glob($dirname."*.jpg");
echo'<div id="slider" class="flexslider"><ul class="slides">';
foreach($imagesas$image) {
    $titel = basename("$image", ".jpg").PHP_EOL;
    echo'<li><img src="'.$image.'" alt="'.basename("$image", ".jpg").PHP_EOL.'"><p class="flex-caption">'.str_replace("_", " ", $titel).'</p></li>';
};
echo'</ul></div>';
?>

Once you have this working replace alert("it worked"); with whatever you want to happen if it's successful, I'm presuming a redirect to your image page.

Solution 2:

You can do a post, it is shorthand ajax for the post method.

$.post('path/to/php', {variable_name: $('#datepicker')}, function(return_data, result, xhr){
    if(result == 'success')
        console.log(return_data); //or do whatever you want, or keep it empty
});

You can then receive this variable again in your php like you would a normal post like so:

$_POST['variable_name']

Post a Comment for "Jquery Datepicker To Php Variable Without Form"