Get Last-Modified date of a file using JS XMLHttpRequest() on IOS - javascript

Here is my problem.
I'm developing an webapp, written in Angular and NOT jQuery, for a client that need to have its database refreshed every week with new sets of data. So they chose to use SQLite3 because they can drop the new DB into a folder and the sales rep can download this DB file every Monday. But there are a series of data that gets cached on localStorage and those data need to be refreshed as soon as the iPad checks the DB file and returns true if is a new file. So, I'm using XMLHttpRequest() to check the head for the "Last-Modified" date and it works perfect on Chrome and Safari, but once I build the app and move to iPad, the Last-Modified date return null. I searched everywhere in the web to try find what could be wrong, but I just could not find any satisfactory answer:
The code I'm using is
var dbPath = "db/myDb.sqlite";
var getMTime = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', dbPath, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var mtime = new Date(xhr.getResponseHeader('Last-Modified'));
if (mtime.toString() === 'Invalid Date') {
callback(); // dont want to return a bad date
} else {
callback(mtime);
}
}
}
xhr.send();
};
Thanks in advance for the help
UPDATE
Looks like the IOS WebView wipes the HEAD object response... So, thats why by running xhr.getResponseHeader I get empty object, but I would love to know if there is an alternative for that and why this object is being wiped...

Related

How do I send user to a link upon successful xhr POST?

I have a working web page, complete with a JavaScript function that displays text messages based on the "non-successful" results, within the same page. Everything is working except this last step.
I need to send a JSON string to my server in a POST, and regardless of outcome, I need the user's browser to navigate to the page returned in the POST. (Just as if it were an ordinary link ( href ="" type of thing.) I am using the custom tag [OK_RESULT_URL] that my server replaces with the real URL just before the page is downloaded.
You see in my code below, that I set the URL to [OK_RESULT_URL] AND the window.location to [OK_RESULT_URL] as well, which seems wrong. That means I'm making two hits to [OK_RESULT_URL], one is a POST with a body (which is correct) and the other one a GET without a body (which is wrong).
I'm a total newbie to JavaScript, so I'm probably missing something obvious. It's as if instead of using xhr.Send() I want to say xhr.SendAndNaviateTo() ... or something like that.
Thanks for any help you can provide.
onApproval: function (response) {
showResult("Approved", JSON.stringify(response, null, ''\t''));
let xhr = new XMLHttpRequest();
let url = "[OK_RESULT_URL]";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200){
window.location = "[OK_RESULT_URL]"};
var data = JSON.stringify(response);
xhr.send(data);
}

How can I stop caching when using AJAX to read a file?

I'm currently building a website that uses AJAX to dynamically update sections of the page without the need to refresh, however, when I change aspects of the file that AJAX reads the website sometimes takes minutes to update even though the file is read about once per second. Whilst looking for the issue I found that I can turn caching off by using the developer tools and this then allowed the website to update at the appropriate speed.
Here's the code I am using:
var path = "Path of the json file i am reading"
var state;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
state = JSON.parse(this.responseText);
}
};
xhttp.open("GET", path, true);
xhttp.send();
I've been looking for a while now and the only advice I can see about what to do about the cache is to use the developer tools to turn it off. Is there any way I can implement some code to automatically tell the browser to not cache the file being read?

Difference between Electron-based XMLHttpRequest and browser-based URL with query string?

I'm working on an Electron app and trying to integrate the Easy Digital Downloads Software Licensing WordPress plugin. I haven't done much with HTTP communication in Electron/Javascript so this may be a naive question.
The problem: I am able to get a license activation response from my EDD server and while there is no specific error, for some reason a license is not activated. The odd thing is that if I use a URL and query string in a browser with the same data, the plugin responds as expected: I can activate, deactivate and check the status of a license.
So EDD seems to be working and there are no errors with Electron. But something is missing. Initially I was using the net Electron module but after this issue came up, I switched to using the example script from EDD (below) which uses XMLHttpRequest. With that I get the following response back:
{"success":true,"license":"valid","item_id":539,"item_name":"My
Awesome App","license_limit":1,"site_count":0,"expires":"2020-12-19
23:59:59","activations_left":1,"checksum":"f2d66c6844b37d1fa931b813c408",
"payment_id":248,"customer_name":"Marvin
Gardens","customer_email":"marvin#home.com","price_id":false}
Which is fine except that "activations_left":1 never changes and it should given "license_limit":1. So something is wrong.
On the other hand, if I use a URL with a query string in a browser, the "activations_left" is decremented and license activation only works once (as it should). For example, this works:
http://YOURSITE.com/?edd_action=activate_license&item_id=8&license=cc22c1ec86304b36883440e2e84cddff&url=http://licensedsite.com
My Question: is there some fundamental difference between these two methods? Is there something I need to add to my XMLHttpRequest? I have a support ticket open with EDD but I need to keep moving with this. And sorry to be so long-winded!
UPDATE:
#aw04 suggested I try using GET – just tried that and I "get" the same response as before: no error but also no activation.
Could there be some property which should (or shouldn't) be in the Electron request which is (or isn't) in a browser request by default?
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log('xhttp.responseText', xhttp.responseText);
}
}
var url = "http://YOURSITE.com/?edd_action=activate_license&item_id=8&license=cc22c1ec86304b36883440e2e84cddff"
xhttp.open("GET", url);
xhttp.send();
var xhttp = new XMLHttpRequest();
var postUrl = 'http://<domain.com>/edd-sl/';
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var data = {
edd_action: 'check_license',
license: '<license key>',
item_name: encodeURIComponent('<item name>'),
};
xhttp.open("POST", postUrl, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "http://local.dev");
var values = '';
for (var key in data){
values += key + '=' + data[ key ] + '&';
}
values = values.substring(0, values.length - 1);
xhttp.send(values);
Based on some help from Easy Digital Downloads support folks, this is resolved.
The issue had to do with a property in their Software Licensing plugin setup: "Do not check URL". I hadn't enabled that with the result that my API call from Electron failed and the one using a browser succeeded because the browser was adding headers that Electron was not.
After enabling "Do not check URL", calls from within Electron work. I guess there is also an option to pass in a URL, but since I am using EDD for licensing desktop software, that didn't seem like a needed option.
Anyway, hope this helps someone.

Send ~HI command to Zebra printer and receive the response in javascript clientside

I'm facing an issue and I cannot find a way to overcome it. If I send a ZPL command to print a label via XMLHttpRequest() like this:
var request = new XMLHttpRequest();
var method = "POST";
var async = true;
var zpl = "^XA...^XZ";
var urlForPrint = "http://192.168.0.242/printer/pstprnt";
var urlForHi = "http://192.168.0.242:9100";
request.onload = function () {
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
}
request.open(method, urlForPrint, async);
request.overrideMimeType('text/plain; charset=unicode');
request.send(zpl);
it all works fine (prints the label). But before trying to print anything, I need to send the command ~HI, which, according to the documentation, should return a string with a number of properties, related to the printer at this IP.
The problem: I cannot receive this string.
var requestForPrinter = new XMLHttpRequest();
requestForPrinter.onerror = function (e) {
//...
}
requestForPrinter.onload = function (e) {
// I suppose that response message should arrive here, as a parameter of e
//...
}
requestForPrinter.open(method, urlForHi, async);
requestForPrinter.send("~HI");
If I use PuTTY, the printer returns the message and it is displayed in the PuTTY console.
After a lot of research, I realized that PuTTY communicates with the printer via TCP/IP, while I'm trying to communicate with it via HTTP. So I have now got a clear idea what is the problem. But how to solve it?
A colleague of mine suggested creating a socket. So I tried WebSocket, TCPSocket, socket.IO with no success. Also, they seem not to be supported by all popular browsers and I couldn't manage to test them because of errors, which appeared in the browser's console. Tried to fix them with no luck.
Any help will be appreciated! Thank you!
edit: I found this. So my second question is: I am just starting to learn node.js and find out its capabilites. I read somewhere, that It is a server-side js library. Can I use it only client-side? I mean, they have to be able to print labels using the printer in their LAN and to be able to work even if the Internet connection drops (to ask the server for data only once, at the beginning, when it loads some data into a JqGrid). So communicating with a server is not an option here.

XMLHttpRequest to the MongoDB simple rest interface

I am a beginner in both Ajax and MongoDB. I was hoping to visualize some of the data in my MongoDB using a web browser (which, for the moment, is running on the same host). For this, I thought it might be possible to get the data using XMLHttpRequests. I am running MongoDB with the --rest option and I checked that when I load hxxp://localhost:28017/test_db/ss_test/
on Firefox, I get the proper reply (a JSON document with the data in the ss_test collection of the test_db database). So far, so good.
I then wrote the following JavaScript function which I connected to the "onclick" of a button:
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
So, when I load the html file on Firefox, open the console and click on my button, I see that the http request is indeed made, the status code is "HTTP/1.0 200 OK" and a response with Content-Length: 219257 is delivered, which looks great. However, the XMLHttpRequest object does not report the status=200. The alerts that pop up report a constant status of 0 as the readyState progressively becomes 1, 2 and 4 and my if statement is never true.
Could anyone please tell me what I am doing wrong? In the beginning I thought it was because my html was loaded on the browser by the file protocol or that I was seeing some same-origin policy related issue, but then I put the html file on a web server on localhost and loaded it from there and nothing changed. Thank you very much for any replies!
you need to create a function to handle the request.
http://www.ibm.com/developerworks/web/library/wa-ajaxintro2/
http://www.ibm.com/developerworks/library/wa-ajaxintro3/
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = create_this_function()
{
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
#
function create_this_function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}

Categories