Home » Php » php – How to pass the jquery datepicker value in form POST method?

php – How to pass the jquery datepicker value in form POST method?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a input text in the form for date and i use JQuery datepicker to select date.

 <input type="text" id="datepicker" name="datepicker" value="Date"/>

when i use form post to post the values into another php for calculation. i don’t get the values from this input text alone. i get an empty value instead of selected date.

 $date=$_POST['datepicker'];

i’m not sure of how to pass the datepicker value in form POST. Can someone help me out?

How to&Answers:

jQuery’s datepicker has nothing to do with posting your form. If your form is set to “post” then whatever is left in that input field after the user has selected a date will be sent with the form.

<form action="process.php" method="post"> 
  <input type="text" id="datepicker" name="datepicker" value="Date"/>
</form>

Gives you:

$date = $_POST['datepicker'];

However if your form is being sent as a “get” request you’ll need to access it as such.

<form action="process.php" method="get"> 
  <input type="text" id="datepicker" name="datepicker" value="Date"/>
</form>

Gives you:

$date = $_GET['datepicker'];

Answer:

$( "#currentDate" ).datepicker("setDate", new Date("<?php echo $_POST['myCurrentDate'] ?>"));

works for me, read at least 10 very complicated ways of doing it and then realised this works. You are instantiating a new value each time. you store the date somewhere in your php scripts, using form input or some other technique and then recycle it back into the above statement. So reloading doesn’t affect the result.

If myCurrentDate is unset it will set it by default. Getting it to be set to today’s date requires a php if statement to set it the first time (or reload the page) to new Date() and the else statement can be used to include the above code.

Answer:

That’s a simple form with a datepicker

   <form id="myform" name="myform">
    <input type="text" id="datepicker" name="datepicker" value="Date"/>
    <input type="button" id="submitMe">
    </form>

Now your jquery,we are going to use some AJAX stuff:

//init datepicker
$(function() {
    $("#datepicker").datepicker({
        showButtonPanel: true
    });
});

//pass deatepicker to php
$("#submitMe").click(function() {
    $.ajax({
        type: 'POST',
        url: "pass.php",
        dataType: "json",
        data: $('#myform').serialize(),
        success: function(data) {
            console.log("Done");

        }
    });
 return false;
});​

And finally your pass.php file

<?php 
//note that date may have slashes or dots so we url decode it

$date = urldecode ($_GET['datepicker']);

echo "chosen date is: ".$date;
?>