I have built a Status Page for my servers with HTML and CSS, and instead of updating the Server Status every time one of them goes down, I was wondering if it's possible to add something to query the IP's of the server every 10m or so, and if the query fails, to turn the status button to RED.
Here's what I'm working with: https://status.floridastaterp.org
Any help is largely appreciated!
Thanks.
You can do it without PHP, for that use javascript and make a ajax call:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// You change the status of button
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
And to call it every 10min, warp your function with:
setTimeout(request(),1000);
function request(){
if(response == true){
// This makes it unable to send a new request
// unless you get response from last request
response = false;
var req = $.ajax({
type:"post",
url:"https://status.floridastaterp.org"
});
req.done(function(){
console.log("Request successful!");
// This makes it able to send new request on the next interval
response = true;
});
}
setTimeout(request(),1000);
}
request();
Related
I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.
Can someone, please, explain to me, why in the code snippet below I get request.response == null?
In my JSON file I have an array with some data, which I want to use further.
After spending a lot of time on finding a problem, I found that there is a problem with link. When I uploaded JSON file into web service and used a link from that, it works fine. But when I use a link to the file in my file system, it doesn't want to work.
let requestURL = "../sliderContent.json";
const request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = () => {
if (request.readyState === 4 && request.status === 200) {
let slidesContent = request.response;
console.log(slidesContent);
returnSlidesReducer(slidesContent);
}
};
hi frnd form last 2 days i am trying to send JSON data to server but is not working i am posting my js file and check if any error. and i am try to send json data by using xmlHttprequest. and if any other function and any change i have to do then plz tell me. i am developing cordova project in eclipse.and if any other thing and any file also have to change then tell me
this is my js file and on click registration button i am calling this method.
function get() {
alert("function is called");
var name_field_value=document.getElementById("name_field").value;
var email_field_value=document.getElementById("email_field").value;
var password_field_value=document.getElementById("password_field").value;
var phone_field_value=document.getElementById("phone_field").value;
var JSONdata= {
"name": name_field_value,
"mobile_number": phone_field_value,
"email": email_field_value,
"password": password_field_value
}
var request = new XMLHttpRequest();
request.open("POST", "http://www.jiyonatural.com/AccountManagements/insert_new_user", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.status);//this alert is working and getting 0 status
if (request.status == 200 || request.status == 0) {
// -> request.responseText <- is a result
/*var tweets = JSON.parse(request.responseText);*/
alert(request.responseText);//this alert is not working//
//if i make other alert then it works
}else{
alert("function is called3");}
}
}
request.send(JSON.stringify(JSONdata));
}
Looks like your question is incomplete.
In my experience the error probably lies in server code friend.
And you should use ajax method in jquery for communication with server.its easier than XMLhttpRequest.
I have a web page that invokes long request on the server. The request generates an excel file and stream it back to the client when it is ready.
The request is invoked by creating form element using jQuery and invoking the submit method.
I would like during the request is being processed to display the user with progress of the task.
I thought to do it using jQuery ajax call to service I have on the server that returns status messages.
My problem is that when I am calling this service (using $.ajax) The callback is being called only when the request intiated by the form submit ended.
Any suggestions ?
The code:
<script>
function dummyFunction(){
var notificationContextId = "someid";
var url = $fdbUI.config.baseUrl() + "/Promis/GenerateExcel.aspx";
var $form = $('<form action="' + url + '" method="POST" target="_blank"></form>');
var $hidden = $("<input type='hidden' name='viewModel'/>");
$hidden.val(self.toJSON());
$hidden.appendTo($form);
var $contextId = new $("<input type='hidden' name='notifyContextId'/>").val(notificationContextId);
$contextId.appendTo($form);
$('body').append($form);
self.progressMessages([]);
$fdbUI.notificationHelper.getNotifications(notificationContextId, function (message) {
var messageText = '';
if (message.IsEnded) {
messageText = "Excel is ready to download";
} else if (message.IsError) {
messageText = "An error occured while preparing excel file. Please try again...";
} else {
messageText = message.NotifyData;
}
self.progressMessages.push(messageText);
});
$form.submit();
}
<script>
The code is using utility library that invokes the $.ajax. Its code is:
(function () {
if (!window.flowdbUI) {
throw ("missing reference to flowdb.ui.core.");
}
function NotificationHelper() {
var self = this;
this.intervalId = null;
this.getNotifications = function (contextId, fnCallback) {
if ($.isFunction(fnCallback) == false)
return;
self.intervalId = setInterval(function() {
self._startNotificationPolling(contextId, fnCallback);
}, 500);
};
this._startNotificationPolling = function (contextId, fnCallback) {
if (self._processing)
return;
self._processing = true;
self._notificationPolling(contextId, function (result) {
if (result.success) {
var message = result.retVal;
if (message == null)
return;
if (message.IsEnded || message.IsError) {
clearInterval(self.intervalId);
}
fnCallback(message);
} else {
clearInterval(self.intervalId);
fnCallback({NotifyData:null, IsEnded:false, IsError:true});
}
self._processing = false;
});
};
this._notificationPolling = function (contextId, fnCallback) {
$fdbUI.core.executeAjax("NotificationProvider", { id: contextId }, function(result) {
fnCallback(result);
});
};
return this;
}
window.flowdbUI.notificationHelper = new NotificationHelper();
})();
By default, ASP.NET will only allow a single concurrent request per session, to avoid race conditions. So the server is not responding to your status requests until after the long-polling request is complete.
One possible approach would be to make your form post return immediately, and when the status request shows completion, start up a new request to get the data that it knows is waiting for it on the server.
Or you could try changing the EnableSessionState settings to allow multiple concurrent requests, as described here.
I am trying to repeat a JSON request in jQuery to check the status of a video encoding job until it is completed. "Processing" would be displayed until the job is finished, at which point the video will be displayed.
Would a loop, checking every x seconds to see if "status" equals "finished," be the best solution for this? If so, how would I break free from this loop when the job is finished?
The JSON response while the job is in progress will be nothing more than "processing," when it is finished it will contain things such as the job ID, width, and height.
Any help would be appreciated, thanks!
UPDATE
Here's my final solution thanks to Felix:
var checkStatus = function() {
$.getJSON('json-data.php', function(data) {
if (data.status != 'finished') {
setTimeout(checkStatus, 2000);
} else {
//Sample code to run when finished
$("#statusText").text("Job Complete");
$("#dimensions").text(data.width + 'x' + data.height);
}
});
};
checkStatus();
A loop won't work as the Ajax request is asynchronous.
One way would be to make same kind of recursive call and trigger the Ajax function again from the success callback (maybe after some timeout), if the condition is not met.
Something like (pseudo code):
function check_condition() {
$.getJSON(<url>, function(result) {
if(!result.finished) {
setTimeout(check_condition, 2000);
}
// do something else
}
}
var checkStatusInterval = 30 * 10000; // 30 seconds
var checkStatusFunc = function(){
$.getJSON('getMovieStatus', function(data){
if (data.Incompleted){ // or however you check
checkStatusTimer = setTimeout(checkStatusFunc, checkStatusInterval);
}
});
};
var checkStatusTimer = setTimeout(checkStatusFunc,checkStatusInterval );
To stop:
<input type="button" id="stopchecking" value="Stop Checking..." />
$('#stopchecking').click(function(e){
clearTimeout(checkStatusTimer);
});