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

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.

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.

XMLHttpRequest refresh only when a change on database is detected

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.

How to make a DELETE http request with Javascript (not jQuery)

I'm trying to figure out how to make a DELETE request using just Javascript. I have a service written in Java Spring where the controller for the url that I am working on has method = RequestMethod.DELETE. My url is, say, http://192.168.50.51/my-service/deleteLocation/{value1}/{value2}/{value3}. In my JavaScript, I have an AJAX function like so:
ajaxFunction : function(url, callback, httpMethod) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var jsonParse = JSON.parse(xhttp.responseText);
callback(jsonParse);
}
}
xhttp.open(httpMethod, url, true);
xhttp.send();
}
When I want to use the DELETE url, I have an event handler attached to a button that runs this method:
deleteConfirm : function() {
var valuel = this.value1;
var value2 = document.getElementById('element-id').getAttribute('data-element');
var value3 = document.getElementById('element-id').getAttribute('data-element2');
var url = 'http://192.168.50.51/my-service/deleteInfo/' + value1 + '/' + value2 + '/' + value3;
var httpMethod = 'DELETE';
var deleteCallback = function() { alert('deleted!'); }
this.ajaxFunction(url, deleteCallback, httpMethod);
}
However, I keep getting an error in my console: my-javascript.js:59 DELETE http://192.168.50.51/my-service/deleteInfo/123456789/123-456-7AB/12699 406 (Not Acceptable).
I've read that XMLHttpRequest only accepts GET and POST. How do I go about making a delete request using just JavaScript?
Given the information, it looks like your browser is actually making a DELETE request, because the server gave you back a 406 (Not Acceptable) response. It wouldn't do that if your client never sent the request in the first place. This means that the server received your DELETE request and decided it wouldn't process it. So you'll need to look at the server's API to see what gives you HTTP406 and what needs to be different about your request to make it work.
A good way to debug these kinds of things is through your browsers developer tools. Most browsers have a tab in there that shows you the HTTP requests and responses that the browser made. It will make it easier for you to verify these things, going forward.

How to check webpage is available or not using javascript

I want to make a web page request only if that web page is available. I have written my app using angularjs + javascript. Is there any way to determine whether a webpage is available or not using javascript ?
If the page in question is on a different origin, you can't without using a server somewhere or relying on the other page implementing Cross-Origin Resource Sharing and supporting your origin, because of the Same Origin Policy.
If the page in question is on the same origin, you can do an ajax call to query it:
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// It worked
} else {
// It didn't
}
}
};
xhr.send();
You can make an AJAX request with XMLHttpRequest, but instead of POST or GET, you should use the HEAD HTTP verb.

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