How to Implement a JavaScript Ping

How to Implement a JavaScript Ping
Page content

Ping Defined

Ping is a method whereby you want to send a signal to a particular IP or domain and to wait for a response from that particular address. Some sort of response code generally means the location not only exists but it is also up and running.

Where You Would Want to Use JavaScript Ping

Not only can you use JavaScript ping to check whether a server is up and running but you can use it to keep a connection to a particular web service or script on a web server live. These services could be something like a currency update service, or stock data reports and so on. You would want to check whether these services are running so that if they are not then you can handle this status appropriately or simply to make sure you maintain a live session such as in the case you do not want to log out your users because they have been idle for a while.

You can send a pre-defined message so as to get a specific response. You can also use another trick which involves requesting a certain file from the web server such as a very small image file and that should be enough to maintain a session. Calling a restricted page should also be good enough. The reason you want to use a small image file or a restricted page is to limit the amount of data that is sent back as the response and save on bandwidth.

A Simple Way to Ping Using an Image

You can determine a particular image you want to use to ping and place it on your web server if you have administrative access or you can link to an existing image on a service in which you do not want the session to expire. Once you determine the image you can use the following sample source code on your web page. Be sure to handle the response appropriately. The responses are the lines marked with the alert("") calls. Depending on your needs, such as if you want this process to go along quietly, those lines can be left out.

Put this JavaScript Ping code in the HTML header.

You can now be able to ping the image using a call to the function as illustrated below anywhere in the HTML Body.

Calling a Restricted File

This method calls a restricted file which could be a HTML file or even an image.

This JavaScript ping code simply requests the restricted file every five minutes.

There is more JavaScript code of interest you might want to look at such as these top JavaScript image rotators and this sample JavaScript delay code.