Monday, 1 March 2021

PHP returns ContentType text/html when function returns json

I am attempting to get a JSON string back from a php call (from javascript). I do something similar in another function that works fine (except I am returning multiple records and calling as the ajax: component of a DataTable (datatables.net) and am not using bind in that function. I don't think my issue is with query / OCI. The query works fine in Toad, and I am using the same code for making the DB connection as in the routine that works.

php code:

require 'openDB.php';
if (!$ora ) {
    return "COULD NOT CONNECT to DB";
}
$rawJson = file_get_contents("php://input");
$params = json_decode($rawJson);
$action = $params['action'];
$jobID = $params['jobID'];

if ($action == 'read') {
    return $jobID;
    //readMaintenanceData($ora, $jobID);
} else if ($action == 'update') {
    updateMaintenanceData();
} else if ($action == 'add') {
    addJob();
} else if ($action == 'delete') {
    deleteJob();
}

function readMaintenanceData($ora, $jobID) {
   
    header('Content-Type: application/json');
    if (! $ora) {
   
        return "COULD NOT CONNECT";
    }
    $getJob = oci_parse(
    $ora, 
    "SELECT JOB_ID, JOB_DESCRIPTION,  INFO_DISTRIBUTION, ACTIVE, JOB_RUNNING_SERVER "
    ."FROM SCRPT_APP.JOB_MONITOR_JOBS "
    ."WHERE JOB_ID = :jobID"
);
 
    oci_bind_by_name($getJob, ':jobID', $jobID);
    oci_execute($getJob);
    $job = oci_fetch_array($getJob, OCI_ASSOC + OCI_RETURN_NULLS);
   
    $job_jason =  json_encode($job);
   
    return $job_jason;
}

function updateMaintenanceData() {}
function addJob() {}
function deleteJob() {}

'''' javascript

async function populateMaintenanceTab() {

var url = "php/maintenance.php";
 var jobID = document.getElementById('jobID').value;
//alert(jobID);
//var rBody = 'action=read&jobID=' + encodeURIComponent(jobID);
const getJob = {
    action: 'read',
    jobID: jobID
};

fetch(url, {
    method: 'post',
    body: JSON.stringify(getJob),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(function(response) {
    return response.text();
}).then(function(text) {
    console.log(text);
}).catch(function(error) {
    console.error(error);
});



}

Here is the js state at the time I call fetch (note: control does transfer to the php but the $_POST variable is not populated)

enter image description here

Many thanks to Phil for his efforts to date.



from PHP returns ContentType text/html when function returns json

No comments:

Post a Comment