Recently, I needed to store details in a remote database using JavaScript. The straightforward approach was to send a GET request to a PHP file on the server.
PHP Script
The PHP file handles the incoming data and inserts it into the database:
<?php
$var1 = (int) $_GET['var1']; // this is a number
$var2 = (float) $_GET['var2']; // this is a float
$var3 = (string) $_GET['var3']; // this is a string
// connect to database
require_once 'database.php';
$result = $db->prepare("INSERT INTO table (var1, var2, var3) VALUES ('$var1', '$var2', '$var3')");
$result->execute();
echo 'success';
exit;
Ensure that all variables are properly sanitized. The script connects to the database, inserts the data, returns a success message, and then exits.
JavaScript Code
To send data to the PHP file, you can use the following JavaScript function:
function ping(url, timeout = 1500) {
return new Promise((resolve, reject) => {
const img = new Image();
let timer;
const start = Date.now();
img.onload = () => {
clearTimeout(timer);
resolve({ status: 'success', url, duration: Date.now() - start, event: 'onload' });
};
img.onerror = () => {
clearTimeout(timer);
resolve({ status: 'success', url, duration: Date.now() - start, event: 'onerror' });
};
img.src = `${url}&cache=${start}`;
timer = setTimeout(() => {
img.src = ''; // Cancel the image load
reject({ status: 'timeout', url, duration: timeout });
}, timeout);
});
}
// Example usage:
ping('https://www.domain.com/file.php?var1=256&var2=3.6&var3=string')
.then(response => {
console.log('Ping successful:', response);
})
.catch(error => {
console.error('Ping failed:', error);
});
This function creates a new Image
object and sets its src
attribute to the desired URL with query parameters. It uses a timeout to handle cases where the request takes too long. The onload
and onerror
events are both considered successful pings, as they indicate that the request reached the server.
You can pass JavaScript variables to the URL by constructing the query string accordingly.