Get Date Header Asyncronously - javascript

As the title says, I want to get the Response Header Date value, but I keep getting the following warning :
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
My code :
function getxmlhttp () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
return new XMLHttpRequest();
}else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
return null;
};
function srvTime(){
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.open('GET',"blank.php",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
console.log("raw " + xmlHttp.getResponseHeader("Date"));
return xmlHttp.getResponseHeader("Date");
};
When I switch this line:
xmlHttp.open('GET',"blank.php",true);
To be true, the value returns NULL.
So can this be done, or do I have to just live with the warning in the console?
Thank you

As your title states, you must make the request asynchronously. That means you have to issue the request and wait for it to complete to get the information. Something like this should work:
function srvTime(callback) {
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { // The operation is complete
console.log("raw " + xmlHttp.getResponseHeader("Date"));
callback(xmlHttp.getResponseHeader("Date"));
xmlHttp = null;
}
};
xmlHttp.open('GET', "blank.php", true);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
};
Note that you must change the signature of your srvTime method. You can't return the data from it, the caller must supply a callback function that receives the date once the request completes.
An example of how you would use this function with the new signature is as follows:
srvTime(function (serverDate) {
document.getElementById("clock").innerHTML = "Game Time: " + serverDate;
});

Related

How to get html source of page, after all it scripts was called?

I'am trying to parse site. The site (i suppose) using scripts and data bases to load data from (dynamically?). And this is my problem... I am trying to grab data through C# (unfortunately i don't have access to code right now) or JS. And it seems like either C# and JS, get only template of the site, but don't wait until all scripts executed. So this is my question, is there any way to get ALL html source? Maybe call scripts somehow. Or make a request, wait for 10 seconds, and then write source html data into variable?
Here is my JS code.
function request(link)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', link, true);
xhr.onreadystatechange = function() .
{console.log(xhr.readyState);};
xhr.send();
let data = xhr.responseText;
var tempDiv = document.createElement('div');
tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g,
'');
return tempDiv;
}
function loadFile(url, timeout, callback)
{
var args = Array.prototype.slice.call(arguments, 3);
var xhr = new XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback.apply(xhr, args);
} else {
console.error(xhr.statusText);
}
}
};
xhr.open("GET", url, true);
xhr.timeout = timeout;
xhr.send(null);
let data = xhr.responseText;
return data;
}
function showMessage (message) {
console.log(message + this.responseText);
}
function include(scriptUrl)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", scriptUrl);
xmlhttp.onreadystatechange = function()
{
if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
{
eval(xmlhttp.responseText);
}
};
xmlhttp.send();
let data = JSON.parse(xmlhttp.responseText);
var tempDiv = document.createElement('div');
tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g,
'');
return tempDiv;
}
All this functions do not work as i want.
This isn't really practical - you're trying to load an HTML page, all associated scripts, then run them on the HTML page as if they were in a proper browser environment, but within your current browser session.
This sort of thing is feasible with the jsdom library if you were running on the server-side (NodeJS), because it simulates browser behaviour: https://github.com/jsdom/jsdom. So you could do
JSDOM.fromURL("https://example.com/", { runScripts: "dangerously" }).then(dom => {
console.log(dom.serialize()); //turn the page back into HTML
});
...to get the whole thing.

Jena Fuseki not working when making an insert query from javascript. No Update parameter error

I have this JavaScript function which aims to insert a keyword in a named graph which belongs to the project Dataset.
function insert(keyword) {
var query = "INSERT DATA {GRAPH <http://test1> {<subj> <pred>'" + keyword + "'. }}";
var endpoint = "http://localhost:3030/project/update";
sparqlQueryJson(query, endpoint, showResults, true);
}
I have executed Jena Fuseki with the --update option. The sparqlQueryJson function is as follows:
function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
var querypart = "query=" + escape(queryStr);
// Get our HTTP request object.
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Code for older versions of IE, like IE6 and before.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support XMLHttpRequests?');
}
// Set up a POST with JSON result format.
xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
// Set up callback to get the response asynchronously.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// Process the results
callback(xmlhttp.responseText);
} else {
// Some kind of error occurred.
alert("Sparql query error: " + xmlhttp.status + " " + xmlhttp.responseText);
}
}
};
xmlhttp.send(querypart);
};
The showResults function is, in my opinion, not very important here, since it takes the results of the query and show them in HTML.
I followed what is discussed here and here, executing the query using the http://localhost:3030/project/update. The thing is that if I execute the same query on top of the local Fuseki server with the same endpoint url by using the web, it works, but from the JavaScript code, it raises the error:
"SPARQL query error: 400 Error 400: SPARQL Update: No 'update=' parameter".
I'm using Ubuntu 16.04 and Jena Fuseki - version 2.4.1.
To solve this problem the =query parameter has to be changed to =update. In addition, a parameter with the type of the query has to be handled, i.e., update or query.
if(type==="update"){
var querypart = "update=" + escape(queryStr);
}else if(type === "query"){
var querypart = "query=" + escape(queryStr);
}
...
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if(type==="query"){
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
}

Calling a XMLHttpRequest continuously

At the moment I am calling a function on a setInterval basis.
This function makes a XMLHttpRequest to my server to get update info. If there is an update available I update an image (using canvas element).
Is this the optimum way to do this sort of thing?
My code:
Calling code:
function StartFeedUp() {
if (tmrStartFeedUp) window.clearInterval(tmrStartFeedUp);
tmrStartFeedUp = setInterval(GetNextImage, 330);
}
My called function:
var isProcess = false;
function GetNextImage() {
try {
if (!isProcess) {
isProcess = true;
var urlTS = '/Cloud/isNewFrames.ashx?alias=' + alias + '&version=' + version + '&guidlogon=' + guidlogon;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, true);
xmlhttp.timeout = 200;
xmlhttp.send();
var nextts = xmlhttp.responseText;
}
isProcess = false;
}
catch (err) {
isProcess = false;
document.getElementById("divMode2").innerHTML = err;
}
}
Other than repeating the XHR call, you can use HTML5 Web Sockets which allows you to maintain a connection to the server, whereby the server would push data as and when needed. Web Sockets are relatively new and so aren't supported by old browsers.
Your XHR is asyncronous so you should be listening on the onreadystatechange event instead of always expecting the response to be available directly after the send() call:
xmlhttp.open("GET", urlTS, true);
xmlhttp.timeout = 200;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
console.log("received " + xmlhttp.responseText);
}
}
xmlhttp.send();

JavaScript XMLHttpRequest.onreadystatechange

I'm attempting to do some AJAX and need to know why this code isn't firing a completed or error alert. I'm in Mozilla Firefox 20.0.1
PLEASE NOTE
This code IS updating the database (I have a select statement reading the exact record verifying it's updating) I'm just unsure as to why I can't get an alert when the response has completed.
I have these GLOBAL (at the top of the javascript page) declared variables.
var AjaxEnginePage;
var ClientInfoPage;
var XMLHTTP;
AjaxEnginePage = "AjaxEngine.aspx";
ClientInfoPage="getClientInfo.aspx";
Creating the connection.
//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable
function CreateXMLHTTP()
{
try
{
XMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
XMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
XMLHTTP = null;
}
}
//Creating object in Mozilla and Safari
if(!XMLHTTP && typeof XMLHttpRequest != "undefined")
{
XMLHTTP = new XMLHttpRequest();
}
}
Tying the connection:
function btnUpdateMe_OnClick() {
var me = encodeURIComponent(document.getElementById("MeTextBox").value);
// construct the URL
var requestUrl = AjaxEnginePage + "?Action=UpdateMe&Me=" + me;
CreateXMLHTTP();
// If browser supports XMLHTTPRequest object
if(XMLHTTP)
{
//Setting the event handler for the response
XMLHTTP.onreadystatechange = handleStateChange(me);
//Initializes the request object with GET (METHOD of posting),
//Request URL and sets the request as asynchronous.
XMLHTTP.open("get", requestUrl, true);
//Sends the request to server
XMLHTTP.send(null);
}
Handle State Change
function handleStateChange(me) {
switch (XMLHTTP.readyState) {
case 0: // UNINITIALIZED
case 1: // LOADING
case 2: // LOADED
case 3: // INTERACTIVE
break;
case 4: // COMPLETED
alert("Success");
break;
default: alert("error");
}
I can provide more code if needed. :( thanks.
Change:
XMLHTTP.onreadystatechange = handleStateChange(me);
to:
XMLHTTP.onreadystatechange = function() {handleStateChange(me);};
You're setting onreadystatechange to the result of calling the function, not to the function.

How to wait for ajax request to complete in javascript when synchronous option is not available?

I'm trying to wait for the AJAX request to complete. It would be easy if the method xmlhttp.open would support async = false but Ant Galio does not support this option and only asynchronous requests are permitted. The question is how can I wait for the callback to be called.
var ajaxFinished = false;
var xmlhttp = new XMLHttpRequest();
this.debug("-- onreadystatechange is being defined");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
ajaxFinished = true;
var data = xmlhttp.responseText;
if (xmlhttp.status == 200) {
that.debug('downloadSettings: SUCCESS');
[...]
} else {
that.debug('downloadSettings:');
that.debug('-- Error: ');
that.debug('-- ResponseText: "'+data+'"')
}
}
}
while (ajaxFinished == false) {
}
this.debug("-- open connection");
xmlhttp.open("GET", requestUrl, true); /* Ant Galio does not support synchronous */
this.debug("-- send");
xmlhttp.send();
I'm looking for some kind of active waiting. I know about another solution but I'm interested in a solution that would not require changing more of the code than is my example above.
Thanks!
yes, you can
function getFile(url) {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("GET", url, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var fileFromServer = getFile('http://somedomain.com/somefile.txt');
w3c definition http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
client . open(method, url [, async = true [, user = null [, password = null]]])
You can't. There is no "active waiting" in JavaScript, there can be only one active execution a time ("single-threaded").
There is a workaround.
Instead of using the the blocking while loop for poll use the nonblocking setInterval()..
so your code might look something like this.
var ajaxFinished = false;
var xmlhttp = new XMLHttpRequest();
this.debug("-- onreadystatechange is being defined");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
ajaxFinished = true;
var data = xmlhttp.responseText;
if (xmlhttp.status == 200) {
that.debug('downloadSettings: SUCCESS');
[...]
} else {
that.debug('downloadSettings:');
that.debug('-- Error: ");
that.debug('-- ResponseText: "'+data+'"')
}
}
}
//Polling function
function checkEvent(){
if(ajaxFinished == true){
//your code i.e xmlhttp.open("GET", requestUrl, true);
}
clearInterval(chkeventid);//Clear Interval via ID for single time execution
}
var chkeventid=self.setInterval("checkEvent()",100);//The poll call
The setInterval method is treated a bit differently in JS as you know so you may use it as against the while loop.

Categories