I have a bare bones AJAX script that calls a PHP page to retrieve data from the database. The database call is definitely working. I am getting the below error in the console which seems to indicate that the php script is returning the entire html of the page rather than just the json object post recordset retrieval, but I am not sure. Please see below for error, ajax code and php code.
Error: SyntaxError: Unexpected token '<', ..."<table sty"... is not valid JSON at parse () at jquery.min.js:2:77349 at l (jquery.min.js:2:77466) at XMLHttpRequest. (jquery.min.js:2:80265)
Ajax Script From Client/UI Page: Change to the cboYear html select fires the database call.
<script>
//This method is the event that is triggered once the document is loaded. That way
//no code is executed in a partial load state.
$(document).ready(function(){
$("#cboYear").change(function(){
var iYear = $('#cboYear').val();
//If a year is selected call the php page to retrieve the db values while passing in the selected year for the where clause
//of the SQL statement
if (iYear != "") {
$.ajax({
url: <?php echo( chr(39) . $_SESSION['Web_Application_Root_Directory'] . 'db_includes/get_DR_Design.php' . chr(39) )?>,
type: 'post',
dataType: 'json',
data: {YearID: iYear},
success: function (response) {
console.log('success start');
console.log(response);
console.log('success end');
//parse json
response = JSON.parse(response);
console.log(response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
console.error('Status:', status);
console.error('Response:', xhr.responseText);
}
});
}
});
});
</script>
PHP Page Which Opens Up Recordset from DB and Returns JSON
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/DR/lib_includes/config.php';
$iYearID= $_POST['YearID'];
$sSQL = "SELECT * FROM tb_Design WHERE Year_ID = " . $iYearID;
$DRDesignArray = [];
$oDB = new cDatabase();
$oRst = $oDB->mOpenRecordset($sSQL);
// Fetch data and convert to JSON
while ($row = odbc_fetch_array($oRst)) {
$DRDesignArray[] = $row; // Add each row to the array
}
// Convert the array to JSON
$jsonData = json_encode($DRDesignArray);
// Output the JSON
mLogString($jsonData);
echo($jsonData);
?>
.phpmanually (typing the AJAX-called URL in your browser's URL bar, hardcodingYearIDin your PHP to test) or simply looking at your browser's network inspector to get the full contents? I suspect you're either receiving a good big error message from your PHP, formatted as HTML; or the URL isn't this of your JSON-generating endpoint, rather anindex.phpor such that calls your "PHP page", but only after having included another PHP responsible of the HTML layout of your site.