I have the following javaScript code:
const getReport = {
jobID: $('#jobID').val(),
startDate: $('#summaryStart').val(),
endDate: $('#summaryEnd').val(),
tableType: 'Summary',
};
$.ajax({
url: "php/reports.php",
contentType: "application/json",
type: "post",
dataType: "application/json",
data: function (d) {
return JSON.stringify(getReport);
},
success: function (response) {
if (response["tableColumns"].substring(0, 4) === "<h4>") { //if html returned here no detail query
} else {
$('#summaryTable').DataTable({
select: {
sytle: 'single',
items: 'row'
},
data: response["tableData"], columns: response["tableData"],
dataSrc: ""
});
}
}
});
And in my php code I have the following (to test values coming accross):
$rawJson = file_get_contents("php://input");
echo $rawJson;
return;
$parms = json_decode($rawJson, true);
$jobId = $parms["jobID"];
The code as stated above the XLR value from Chrome’s developer tools is blank. If I run with this code instead:
$rawJson = file_get_contents("php://input");
// echo $rawJson;
//return;
$parms = json_decode($rawJson, true);
$jobId = $parms["jobID"];
I get:
Warning: Trying to access array offset on value of type null at the statement: $jobId = $parms["jobID"];
Note: when I get the warning message, javascript executes my success: routine, but the response appears to be null or blank.
I do a similar thing with fetch
in another part of the app and it works. I could probably switch to that method, but would like to know why my jQuery call does not work.
2
Answers
The
data
option can’t be a function. So this:should be:
The
data
parameter of $.ajax does not take a function it takes a PlainObject or String or Array. Also dataType for JSON isjson
not the json content typeapplication/json
.