getButterfly Logo getButterfly

I have recently needed to store details in a remote database using Javascript. The obvious choice was a GET request and a PHP file on the remote end.

The PHP file looks like this:

$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', '$var13')");
$result ->execute();

return 'success';

Note that all variables are picked up using $_GET and they need to be properly sanitized. I also need to connect to the database or include the connection file. The action returns a string ("success" in this case) and then dies.

The Javascript code to ping the PHP file looks like this:

$.Ping(',6&var3=string').done(function(success, url, time, on) {
    console.log("ping done", arguments);
}).fail(function (failure, url, time, on) {
    console.log("ping failed", arguments);

Note that you can pass Javascript variables to the URL.

And, finally, the actual Ping() function looks like this:

 * URL Ping
 * Useful for cross-origin calls when information
 * can be posted via parameters and collected via GET
jQuery.extend($, {
    Ping: function Ping(url, timeout) {
        timeout = timeout || 1500;
        var timer = null;
        return jQuery.Deferred(function deferred(defer) {
            var img = new Image(),
                start = new Date();
            img.onload = function() {
            img.onerror = function() {
            }; // onerror is also success, because this means the domain/ip is found, only the image not;

            img.src = url += ('?cache=' + start);
            timer = window.setTimeout(function timer() { fail(); }, timeout);

            function cleanup() {
                timer = img = null;

            function success(on) {
                defer.resolve(true, url, new Date() - start, on);

            function fail() {
                defer.reject(false, url, new Date() - start, 'timeout');

That’s it!

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply