Search code examples
phpajaxcurlfetch-api

pHp cURL works fine when run through browser call and CLI, but fails in an ajax/fetch call


TLDR: My php file executes a curl request fine when you go to the URL or CLI, if I call this php file from the site URL using ajax or fetch, I get no response and no error codes. Just blank respone.

EDIT** I found the server logs for my AWS script. It is receiving the POST request. [07/Sep/2024 15:44:00] "POST /update_synopsis HTTP/1.1" 200 -

I have a API hosted on AWS that I send JSON to. This was working fine 6hrs ago. I made no changes to the code, and now the cURL I send data to the API with is broken. I have a .html page that calls a php file on button press.

$.post('./send.php', toForward, function(response) {
            console.log(response);
            console.log("submit")
        }, 'json');
//OR
$.ajax({
            url: 'omittingTheURL.com/send.php',
            type: "POST",
            dataType: "json",
            success: function(data) {
                console.log(data + "test"); // Alert the results
            }
        });

I have dumbed down the code into a debug state and eliminated the reading of the sent JSON (toForward). Here is the php file. I have tried a few things with headers just in case its a CORS issue, but I get no CORS errors. I know jQuery is a google thing, so not sure if its sending through googles URL?

if (isset($_SERVER['HTTP_ORIGIN'])) {
    // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a
    // whitelist of safe domains
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}
$json = json_encode(array('appliancePrompt'=> 'This is a test. Say potato.'));
$url = 'https://flask-service.6pkt8q75gkone.us-east-2.cs.amazonlightsail.com/update_synopsis'; //Mechanic AI API
$data = json_decode($json, true);
// Convert data to JSON format
$jsonData = json_encode($data);
echo $json;

// cURL setup
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
));

// Execute the request
$response = curl_exec($ch);
curl_close($ch);
echo $response;

Whenever I run the code with the cURL function, it doesnt output anything. No error logs at all. No echos from the lines above the cURL either. I dont even get my echo $json output for some reason when I run the cURL. If I comment out the curl execute then I get my echo returns and everything looks proper. The JSON is formatted fine for my receiving end. I cant stress how much that this was working hours ago and I made 0 changes to it. I also dont understand why it works using the phps browser slug but NOT a fetch/ajax/jquery request.


Solution

  • I was hosting the receiving side of my API with AWS Lightsail. AWS Lightsail seems to do some kind of load shedding/server distribution that every couple of days it would transfer servers my app was hosted on and cause CORS issues to occur (Where some of the servers didnt have this CORS issue due to different headers). Since im on AWS Lightsail and not AWS Cloudhost I didnt have access to any kind of error log to see this issue since cURL in php doesnt give out a CORS error.

    I moved away from AWS Lightsail to host this app and no more CORS issues!