I have never used JQuery before - and I am trying to use it to call a PHP script.
However it appears not to work - can anyone explain why?
The PHP is:
error_log("In PHP...",3,"logs/dbc.log"); //<============================= Testing
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['year'])) {
$year = $_POST['year'];
//$year = 2024; //<=======================================================Testing
error_log($year,3,"logs/dbc.log"); //<================================== Testing
$conn = new mysqli('localhost', 'root', '', 'ddbc');
if (!$conn) {
die('Could not Connect to Database' . $conn->mysqli_error);
}
$sql = "SELECT Month, Filename FROM newsletters WHERE year = ? ORDER BY Month ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $year);
$stmt->execute();
$stmt->bind_result($month, $filename);
$results = array();
while ($stmt->fetch()) {
// Convert month number to 2-digit string
$formatted_month = sprintf("%02d", $month);
// Add month and filename pair to the results array
$results[] = array("month" => $formatted_month, "filename" => $filename);
}
$stmt->close();
$conn->close();
$json_data = json_encode($results);
error_log($json_data,3,"logs/dbc.log"); //<============================ Testing
exit;
}
If I comment out the main if loop and initial $year = $_POST[‘year’]; line, uncomment the $year=2024 line and then call the script directly it works exactly as expected. However if I call it from the jQuery it doesn’t appear to be called (no error log output)
The jQuery:
$(document).ready(function () {
$('#yearCmbo').on('change', function () {
$('#months .btn').attr('disabled', 'disabled'); //Works ok
$('#months a').attr("href", "#"); //Works ok
var selectedYear = $(this).val();
$.ajax({
url: 'get_links.php',
method: 'POST',
dataType: 'json',
data: {year: selectedYear},
success: function (response) {
var obj = $.parseJSON(response);
// Need to parse the array and but below for testing
alert(obj);
},
error: function () {
alert("did not work");
}
}); // end of ajax call
}); // end combo change
// Initially force call to combo change function to display data for current year
$('#yearCmbo').change();
}); // end of ready function
I assume it must be something to do with the way I have setup the $.Ajax function, but it looks ok to me based on other examples I have seen online.
Many thanks for any comments