Reading from a http-get presenting in Firefox bookmarks - javascript

I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.
My quesion then is: Does anyone have any sample code that will do this?

Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4) { // Done loading?
if(this.status == 200) { // Everything okay?
// read content from this.responseXML or this.responseText
} else { // Error occurred; handle it
alert("Error " + this.status + ":\n" + this.statusText);
}
}
};
xmlhttp.send(null);
A couple of notes on this code:
You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found here.
You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
You may want to do things when earlier readyStates are received. This page documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.

Robert Walker did a great job of describing how to send the request. You can read more about Mozilla's xmlhttprequest here.
I would just add that the response would be found (using Robert's code) using
xmlhttp.responseText
(Edit - i didn't read closely enough, thanks Robert)
You didn't indicate exactly what the data was, although you mentioned wanting to parse links from the data. You could the xmlhttp.responseText as an xml document, parse out the links, and place it into a menulist or whatever you like.

Related

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.

cannot manipulate response from xmlHttpRequest 2

I'm using XHR 2 to upload/save files.
According to the response of the server I want to perform an action. For example if the responce is "Saved" I want to hide a div or if the response is "Not Saved" I want to show another div etc...
I implemented what appears to be a simple code that should be working , but is not
Here is the snippet of the XHR
//initialize
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.responseType="text";
xhr.onload = function() {
//if all ok....
if (xhr.status === 200)
{
//update html5 progress bar
progress.value = progress.innerHTML = 100;
//get the respnse
var data=xhr.response;
//convert it to sting - kind of overkill, I know, but I'm stack
var data2=data.toString();
//alert it -- works
alert('data2 '+data2);
//now, do something, according to the response -- NOT working, never alert anything
if (data2=="Not Saved"){alert('Ooops, not saved');}
if(data2=="Saved"){alert('It's all good');}
if(data2=="File too big"){alert('hey, you are watching Jake and Amir');}
document.getElementById('imagesaved').innerHTML=data;
}
//refers to if (xhr.status === 200)
else {document.getElementById("imagesaved").innerHTML="Connect to server failed";}
What is wrong here? This should be working right? Any suggestions?
Thanks
EDIT
I put the alerts for testing. What I actually want to do is call some functions.
If I put
if (data2=="Not Saved"){functionOne();}
if(data2=="Saved"){functionTwo();}
if(data2=="File too big"){functionThree();}
the functions never get called
if I put
if (data2!="Not Saved"){functionOne();}
if(data2!="Saved"){functionTwo();}
if(data2!="File too big"){functionThree();}
ALL the functions are called!!!
I still dont get it...Maybe its something with the response? Or the onload function?
Thanks again
What I finally did is make the server response with numbers, not text. So encoding does not matter any more...
This is the code
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200)
{
var data=xhr.response;
if(data==1)
//say to the user is saved
{document.getElementById('imagesaved').innerHTML="Saved";}
//say to the user, there was an error
else{document.getElementById('imagesaved').innerHTML="Error";}
}
//say to the user that connection to the server failed
else {document.getElementById("imagesaved").innerHTML="Cannot connect";}
};
xhr.open('POST', 'upload.php');
xhr.send(formData);
This is a workaround. I dont know if its the right way to solve this problem , technically. I decided to post it anyway, to help others to quickly solve similar problems. If anyboy else has a better way to suggest , please do.
In this line : if(data2=="Saved"){alert('It's all good');}, you have to escape " ' ".
So convert it to : if(data2=="Saved"){alert('It\'s all good');}
Are you sure that the response of your ajax is text/plain ?
Look on the console (ctrl+shift+i on chrome, F12 on firefox), on net or network tab.
Look on console tab if you got some javascript errors too.

Unable to Parse xml DOM (from file) with java script

I've recently begun running into problems with javascript when I attempt to load element tags from a separate xml file into an html document. I know that I have enabled either XMLHttpRequest or activeX (depending on the internet browser) correctly, but I'm having problems getting the xml file and opening it to access it's tags. In order to open the file, I tried to use:
xhttp.open("GET",filepath,false);
xhttp.send();
xmlDoc=xhttp.responseXML;
the code appears to make it past the first line, but it gets tripped up at the second. I'm wondering if someone would be able to clarify the function of .send(), and if server permissions may by at fault; IE 7/8 it tells me "access is denied" when this block of code runs.
Make sure that ajax requests are sent to the same domain from the resources were accessed.
Taking your code sample here,
xhttp.open("GET",filepath,false);
xhttp.send();
You have requested for a resource with HTTP method GET. This request will be fired only once the send() method is called on the XHR object according to the specification[1]. The arguments for send() will be ignored if the method is GET.
Now once the xhr object is created, it goes through different states[2] such as
UNSENT (numeric value 0)
OPENED (numeric value 1)
HEADERS_RECEIVED (numeric value 2)
LOADING (numeric value 3)
DONE (numeric value 4)
The moment the request is fired(ie , the send() is called), the xhr object will have a state of OPENED.
Now, if we look at the 3rd line of your code "xmlDoc=xhttp.responseXML;", it is quite unclear at what state you are trying to read the content. The best way to read the content is when the state reaches 4 or DONE
Just modify your code as given below:
var xhr = new XMLHttpRequest();
xhr.open("GET", somefilepath, true);
xhr.send();
xhr.onreadystatechange = function() {
if(this.readyState == 4) {
xmlDoc=xhr.responseXML;
}
}

Comet (long polling) and XmlHttpRequest status

I'm playing around a little bit with raw XmlHttpRequestObjects + Comet Long Polling. (Usually, I'd let GWT or another framework handle of this for me, but I want to learn more about it.)
I wrote the following code:
function longPoll() {
var xhr = createXHR(); // Creates an XmlHttpRequestObject
xhr.open('GET', 'LongPollServlet', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
...
}
if (xhr.status > 0) {
longPoll();
}
}
}
xhr.send(null);
}
...
<body onload="javascript:longPoll()">...
I wrapped the longPoll() call in an if statement that checks for status > 0, because I encountered, that when I leave the page (by browsing somewhere else, or by reloading it), one last unnecessary comet call is sent. [And on Firefox, it even causes severe problems when doing a page reload, for some reason I don't fully understand yet.]
Question: Is that status check the correct way to handle this problem, or is there a better solution?
My current answer - until proven false - is, that the solution is correct.
i like the simplicity of this loop.... i think the server side script has to sleep or atleast loop until it gets new data before its considered long polling though this is just normal polling. i would also add something to check if the reques fails though. wrapping that in a try catch bloch should do the trick

Problem with making a simple JS XmlHttpRequest call

Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.
I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!
As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:
function doRequest() {
var req_url, req_type, body;
req_url = document.getElementById('server_url').value;
req_type = document.getElementById('request_type').value;
alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
req = new XMLHttpRequest();
req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
req.onreadystatechange=function() {
if (req.readyState == 4) {
alert(req.status);
}
}
req.send(null);
}
When I run this on FF, I get a
Access to restricted URI denied" code: "1012
error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.
Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.
For security reasons, you cannot use AJAX to request a file from a different domain.
Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.
Instead, you can write server-side code on your domain to send you the file.

Categories