XMLHttpRequest refresh only when a change on database is detected - javascript

My Ajax function is refreshing all the time, and I'd like it to just refresh when a change in a database is detected. Is there a way of doing this?
MY CODE:
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if (req.readyState == XMLHttpRequest.DONE && req.status == 200) {
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET', 'chat.php', true);
req.send();
return false;
}
setInterval(function(){ajax();}, 100);

If you want to have server-push, you can use either Server Sent Events or a Websocket, instead of polling from the client with XMLHttpRequest.
You would have to detect a change in the database on the server side, and then push the change to the webpage using SSE or a websocket, or, alternatively, send a flag that there has been a change, and then pull the change from the webpage using XHR as you are doing now.
I don't know enough about your set-up to provide you with code examples, but there are plenty of examples on the interwebs showing how to do this, with either SSE or a websocket.

Related

How to send HTML document element to server in Node JS from client?

I am trying catch a snap of my client side document object and send it across to the node js server.
But when I try to stringify the
JSON.stringify(document.documentElement)
I am not able to do so. It becomes an empty object.
I want to save the client side document object as an HTML file in server side, do some minor modifications there(replacing relative links and all) and serve it back when we hit our server.
How do I do it then ?
here is what I am trying on client side
if (request.action == "take_snap") {
var base = document.querySelector('base');
base.remove();
var doc = document.documentElement;
const req = new XMLHttpRequest();
const baseUrl = "http://localhost:3000/";
req.open("POST", baseUrl, true);
req.setRequestHeader("Content-type", "application/json");
req.send(JSON.stringify(doc));
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log("Got response 200!");
}
}
}
Any other viable approach here ? Or how do I achieve whatever I am trying.
Please help.
JSON.stringify() expects JSON as an argument which converts it into a string. The html you are reading isn't JSON.Can you try removing the JSON.stringify() from the document.documentElement and check the logs of the nodejs server.

Security of GET vs. POST when using Ajax

I used ajax to send the data. I was successful in implementing it using two different approaches:
1) Using method 'POST' and sending data in send() method by setting requestheader.
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send("userName=xyz&password=abc");
2) Using method "POST" and appending parameter values in the URL as:
var xmlHttp = getXMLHttpRequest();
var url="login.do?userName=xyz&password=abc";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send();
Since this is an ajax call, URL will not be visible in the browser window, so I wanted to know which approach is better and why?
Thanks in advance
Here is W3 recommendation for you.
That pretty much says what exactly you need to do.
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead.
Though it is saying post, internal meaning of it is to keep the URL clean.
Apart from the given two ways, if I were you, I prefer clean codes (imagine 10 query param).
var data = new FormData();
data.append('userName', 'xyz');
data.append('password', 'abc');
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send(data);
Putting data into the URL's query parameters doesn't make it a GET request. A POST request is a POST request; the difference is between sending data in the URL or sending it as POST body. There's no fundamental difference between both in this case, the data is equally (non) visible for anyone who cares to look.
The only arguable difference in security is that the URL will likely be logged by the server and/or proxies, while body data usually isn't. But then again, you're already sending the data to the server you presumably trust, so even that doesn't make much of a difference. And the server(s) could be logging the body as well if they wanted to.
Semantically I'd send the data in the POST body, but that's not because of security.

The simplest way of websocket based on vanilla JS AJAX long polling

I prepare the simplest way of AJAX long polling (realtime) in vanilla JavaScript, without any libraries like jQuery...
The code works based on timestamp of data.txt read by PHP file server.php (that's all).
function realtime(timestamp) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'server.php' + (typeof timestamp !== 'undefined' ? '?timestamp=' + timestamp : ''), true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
document.getElementById('response').innerHTML = result.content;
realtime(result.timestamp);
}
};
xhr.send();
}
realtime();
Now, I would like to know how to prepare similar example in websocket (without any libraries, just clean JS/PHP).
It is possible?
Websocket is a different protocol than HTTP (it uses the HTTP upgrade mechanism).
So you'll have to adapt your webserver AND any reverse proxy etc. to handle websocket connections.

Safe Way to Send POST Request via Javascript

I'm currently sending POST requests to a PHP file of mine via a button with the following function:
function buttonFunction() {
$.post("http://ipaddress/core/file.php",{username:username, password:pword, coins:coins}, function(data) {
// Stuff
});
}
However, I recently found out that if the file process/PHP script is still running (trying to obtain the resulting data/response), and the user refreshes the page, the PHP process would still be running on the server. Also, if the user then decided to click the button again (after refreshing), there would be TWO PHP proccesses running from the same user on the server (that is, if the first one was still running):
Javascript Abort POST Request on Retry/Refresh (HIGH CPU Usage)
However, I came across sending POST data with XMLHttpRequest with Javascript:
Send POST data using XMLHttpRequest
So let's say I send my POST request this way, would it be safe to say when the user refreshes/closes out of the page, the PHP execution ends?
function buttonFunction() {
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
However, if this also does not work, how can I fix this issue (multiple scripts running in the background from the same user)? Whether that fix be in the PHP file or in the JavaScript itself, any help would be appreciated.
Edit 1:
Possible Solution?
What if I use XMLHttpRequest and abort the request before the page unloads?
window.onbeforeunload = function(event) {
http.abort();
};

Check if a remote JSON is newer than the local one without download the entire file in Javascript

I'm creating a Phonegap app that check if a local JSON is up to date comparing it with the last Remote version of it. If the remote version is newer than the local the program will update the local JSON.
To avoid bandwith waste I would like to do the version check without downloading the whole remote data. Just checking the headers... I guess...
Looking for a solution I found that some people talk about "HTTP ETag header" like in this thread
Does somebody know How could I implement something like that in pure Javascript?
Thanks in advance.
If your server sends the correct response type of
304 - Not modified you can check for an update with something like this
function hasUpdate(url, callback)
{
var http = new XMLHttpRequest();
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
if (this.status === 200) {
// Data is new -- maybe do another request and grab a copy?
} else if (this.status === 304) {
// Data is not modified
} else {
// Something else happened.
}
}
};
http.send();
}

Categories