I’ve got a simple chrome extension that is using Jquery and works on a page on our local network.
When that page is loaded jquery reacts to clicks on an element called #site
and then calls a php page. This has been working for the last 6 months without issue.
Normally the test.php page is run once and looking at the error_log I would see one row of debug output. I’ve recently moved test.php to a new server and since then it appears to be triggering twice. Looking at the apache2 error_log I see the same row of debug output twice.
This is a simplified version of the code I’m using to try to work out what is happening.
$("body").on('click', '#site', function(e) { url = "https://192.168.0.1/test.php' console.log ( url ) $.ajax({ type: "GET", url: url, cache: false, success : function(text) { console.log (text) } }); })
For testing, test.php contains:
<?php $now = time(); error_log ( $now ); echo $now; exit; ?>
When I click on the #site
element I see one row of output in the browsers console. That shows the URL called and the resulting timestamp from test.php
However looking at the apache2 error_log I see two rows of output. eg:
[Mon Jan 17 10:12:19.993783 2022] [php7:notice] [pid 17508] [client 192.168.0.1:5173] 1642414339 [Mon Jan 17 10:12:19.994898 2022] [php7:notice] [pid 17508] [client 192.168.0.1:5173] 1642414339
When I’m running this with live code the php page is doing a database insert and it results in two entries being added.
I’m trying to work out why the php page appears to be run twice. Can anyone advise what may be causing this and how to resolve it. I have checked and nothing else is bound to #sites
Thanks
UPDATE
After looking looking at the network tab of chromes console I could see two requests, one Preflight and the other xhr.
Adding the following to my test.php script does seem to have resolved it.
$method = $_SERVER['REQUEST_METHOD']; if ($method == "OPTIONS") { header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization"); header("HTTP/1.1 200 OK"); die(); }
So the page is only returning headers to preflight cors check, not running the code.
Advertisement
Answer
Following @JohnSmith’s advise I checked the network tab to see if multiple requests were being sent.
From that I could see two entries, Preflight and xhr. Google pointed out what the Preflight message was and adding the following to my test.php page appears to have resolved the issue.
$method = $_SERVER['REQUEST_METHOD']; if ($method == "OPTIONS") { header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization"); header("HTTP/1.1 200 OK"); die(); }