Is possible do a ping to a server and know if the server is online or offline without use AJAX?
I found this code but use AJAX
function pingURL() {
// Getting the URL from the User
var URL = $("#url").val();
var settings = {
// Defining the request configuration
cache: false,
dataType: "jsonp",
crossDomain: true,
url: URL,
method: "GET",
timeout: 5000,
headers: {accept: "application/json", "Access-Control-Allow-Origin": "*",},
// Defines the response to be made
// for certain status codes
statusCode: {
200: function (response) {
document.getElementById("outputDiv").innerHTML="<h3 style='color:green'>Status 200: Page is up!";
},
400: function (response) {
document.getElementById("outputDiv").innerHTML="<h3 style='color:red'>Status 400: Page is down.</h3>";
},
0: function (response) {
document.getElementById("outputDiv").innerHTML="<h3 style='color:red'>Status 0: Page is down.</h3>";
},
},
};
// Sends the request and observes the response
$.ajax(settings).done(function (response) {
console.log(response);
})
.fail(function (response) {
console.log("Error" + response);
});
}
I also other code:
function ping(extServer){
var ImageObject = new Image();
ImageObject.src = "http://"+extServer+";
if(ImageObject.height>0){
alert("Servidor en Linea !");
} else {
alert("Servidor fuera de linea :(");
}
}
Hovever with this last code , the system alway return OffLine
When you post code you need to format it. You can either highlight all the code and press the </> icon or add a line containing nothing by 3 backticks ``` both before and after the code. I have done it for you this time.
Well the imageobject will have no height if what you make the SRC isnt an image.
If you go back and look at the code you copied, you’ll see they’re pulling an image file from the remote server.
Let’s clarify a few things;
You’re not pinging. That’s a specific request type (ICMP), that Javascript cannot mimic. What you’re doing is making an HTTP request to the server.
Your request will be JAX. It may be AJAX, it may be SJAX (Yes, i’m inventing that term).
Why are you so opposed to the AJAX method? It’s the “right” way to do it…
Yes, because $ is a jQuery reference. So it wont be defined if you dont have jQuery loaded.
If you’re trying to do the ajax request purely in vanilla JS;
const myRequest = new Request(aURLgoeshere);
fetch(myRequest).then((response) => {
if (response.status == 200) { //Do whatever you were gonna do for a 200. }
else { //Do something else. }
});
Looks like you’re bouncing off the CORS of the server you’re trying to check. This is not unexpected. If the target URL’s CORS does not allow cross-origin requests, the fetch will fail.