Reputation: 3
I have a page with a jQuery Datepicker. Once the value is selected, I want to be able to store it in a PHP variable, so I can compare it with a variable I am getting from an Advanced Custom Fields component.
The code to setup my Datepicker and store the value in a JS variable:
<input name="reviewdate" type="text" id="datepick" /> <button id="searchperf">SEARCH</button>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function () {
$("#datepick").datepicker({
minDate: new Date(2023, 4, 23),
maxDate: 0
});
});
$('#searchperf').click(function() {
$perfdate = $('#datepick').val();
$formatcastdate = $('#datepick').val().replace(/\//g, '');
});
</script>
and the code to store the value from the datepicker in a PHP variable:
<?php
if(isset($_GET["reviewdate"])) {
$date = date_create($_GET["reviewdate"]);
echo($date);
echo var_dump($date);
} ?>
Right now, I can store the value in a jquery variable, but I can't store it in a PHP variable... Whenever I try to output $date, it doesn't show anything.
Upvotes: 0
Views: 38
Reputation: 603
To store a JavaScript variable value into a PHP variable, you can't directly assign it because PHP is a server-side language and JavaScript runs on the client-side.
So you need to write php script like create a new file with xyz.php name
and in that file
if (isset($_POST['reviewdate'])) {
$date = date_create_from_format('m/d/Y', $_POST['reviewdate']);
$acf_date = get_field('date_field', 'page');
echo json_encode(['status' => 'success', 'message' => 'Date processed']);
} else {
echo json_encode(['status' => 'error', 'message' => 'No date provided']);
}
after that change your JS with this
$(function() {
$("#datepick").datepicker({
minDate: new Date(2023, 4, 23),
maxDate: 0
});
$('#searchperf').click(function() {
var perfdate = $('#datepick').val();
$.ajax({
url: 'xyz.php'
type: 'POST',
data: { reviewdate: perfdate },
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.log(error);
}
});
});
});
Upvotes: 0