robert robert - 1 year ago 61
Javascript Question

PHP not getting POST data from $.ajax

I have a JavaScript that runs a POST method once my datepicker has been out of focus (I also tried this on a regular submit button) and runs the script

. The PHP runs, however it doesn't get past the if-statement because my it's not getting the POST data. The datepicker is tied to a input field

if (selectedDateFrom.length > 0) {


type: "POST",
url: "include/rent-fetch-pick-up-point.php",
data: {action: selectedDateFrom},
success: function(data) {

Here is the PHP code:

if (isset($_POST['time-period-from'])) {
require '../include/connection.php';

$dateFrom = $_POST['time-period-from'];
$sql = "SELECT * FROM order WHERE $dateFrom BETWEEN date_from AND date_to";
$result = mysqli_query($connection, $sql);
$numRows = mysqli_num_rows($result);

echo $sql; // For testing purposes

And here's the HTML:

<input type="text" name="time-period-from" id="datepicker-from" class="datepicker"></p>

I also tried using $.post() instead of $.ajax(), but I ran into the same issue:

$.post("include/rent-fetch-pick-up-point.php", {name: selectedDateTo}, function(data) {



Answer Source

The keys of $_POST come from the keys of the object you pass to the data: option, not the names of the form fields where the values originally came from. Since you used:

data: { action: selectedDateFrom }

the value will be in $_POST['action'], not $_POST['time-period-from']. So you need to use:

if (isset($_POST['action']))


$dateFrom = $_POST['action'];

or you could change the Javascript to:

data: { "time-period-from": selectedDateFrom }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download