How can I use a ping in Javascript to evaluate an IF statement?

Welcome to my first post on this forum!

I am working on a project for a mobile browser (specifically Android). I am trying to determine if a computer is turned on before deciding which function to execute.

Is there a way to ping the computer to check its network presence and then run the appropriate function? Right now, I am just displaying test messages. Please note that I am using navigator.notification.alert method in Cordova to show messages on the mobile device.

I have come up with some code, but it doesn't seem to be working. I tried searching online without much success.

Keep in mind that this needs to work within a local network.

function isOn() {
    $.ajax({
        url: 'http://192.168.x.xxx', // x.xxx being the client ip
        success: function () {
            navigator.notification.alert(
                'The computer is on.', // Message body
                alertDismissed, // Callback
                'The Computer is On', // Title
                'Yes' // Button Label
            );
        },
        error: function () {
            navigator.notification.alert(
                'The computer is off.', // Message body
                alertDismissed, // Callback
                'The Computer is Off', // Title
                'Yes' // Button Label
            );
        }
    });
};

<a onclick="isOn();">Test</a>

Answer №1

In order to access a URL, it cannot simply be an IP address. A document must be requested for the connection to be successful. If your client does not have a functioning web server, you will encounter an error.

Therefore, if you need to ping a computer, you should utilize a server-side script like this:

$.post('http://myserver.com/ping.php', {'ip': '111.222.123.123'}, function(data){
  // insert your code here
});

On the server side, you can implement something similar to this:
which allows for pinging clients and returning the results in JSON format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize jQuery and Ajax for Efficient Record Insertion and Loading

I've been diving into the world of jQuery and Ajax, and stumbled upon an excellent tutorial for inserting and loading records. This helpful tutorial Despite successfully storing the comments in the database, I'm facing an issue where the insert ...

What is the best way to organize a complicated array of arrays in JavaScript?

Within my code, there exists an array known as generationArray. Each array contained within generationArray consists of 252 elements. The first 250 elements serve as internal coding data, while the final two positions are designated for sorting criteria. T ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

Adjust the background of the page at regular intervals

I currently have: <script type='text/javascript'> var imageID=0; function changeimage(every_seconds){ //change the image if(!imageID){ document.getByTagName("body").src="icwXI.jpg"; imageID++; } else{if(imageID==1){ document.ge ...

How can I extract an array of objects from a response in Angular?

Arrange array of objects from the received data. Here is the data that I received. [ {name:someName, value:20}, {name:"", value:21} {name:someName, value:25} {name:someName , value:27} {name:"", value:21} {name:someName, value:20} ] I am looki ...

Double scroll event firing in Internet Explorer due to Jquery

Here's the code snippet I've implemented that triggers an ajax call when a div reaches the bottom as part of an auto-dynamic scroll feature. This ajax call fetches the next set of items from the list. $("#gvContacts").scroll(function(){ va ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

Looking to display all items once the page has finished loading

I am experiencing a minor issue. Every time I access my store page where all products are listed, I have to click on the size filter to load the products. This is not ideal as I want all products to be displayed automatically when the page loads. What modi ...

dividing values for future angular use

Within my code, I have the following snippet: color: {{item.color}} This setup functions well when dealing with single items. However, there are instances where I encounter a value such as: white|black Is there a way to separate these values into indiv ...

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...

What is the trick to have a CSS element overflow the boundaries of its containing div entirely?

Currently, I have a JS Fiddle project where I am attempting to achieve a specific effect. In the project, there is a circle positioned at the center of a div. When the script runs, the circle expands evenly in all directions until it reaches the borders on ...

The 'HTMLButtonElement' type cannot be assigned to a 'string' type in TypeScript, error code: 2322

In my code, there is a function that generates "tr" and "td" elements within a table. Using a For Loop, I successfully insert "td" elements into "tr". While everything is working as expected, Visual Studio Code is throwing an error. Below is the code snip ...

Incorporate Object names and Variable names in Javascript programming

I have an object named res and a variable named lea. I need to concatenate. For example: let lea = "abc"; let res = { abc:'steve' }; console.log(res.lea); So my output should be steve. I tried it like this: console.log(res.`${lea}`); ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

Ways to add a substantial quantity of HTML to the DOM without relying on AJAX or excessive strings

Currently, I am looking to update a div with a large amount of HTML content when a button on my webpage is clicked. The approach I am currently using involves the .html() method in JQuery, passing in this extensive string: '<div class="container-f ...

What is the best way to retrieve a JSON key in ReactJS?

I am currently facing a rendering issue. In my componentDidMount function, I am using axios to make a GET call and then updating the state with the received JSON data. The problem arises when I try to access the keys of the JSON in the render method becau ...