Parsing information about the latest GitHub commit - javascript

I've been trying to retrieve information about the latest commit of a specific repo using Javascript, but without many results.
I've been using a XMLHttpRequest to get the data from the repo's commits page (for example: https://api.github.com/repos/trapped/rotmg_svr/commits), but seems like it returns null.
Also, I tried to use regular expressions to get the first match of specific line values (for example, to get the value of the commit description, I used this one: "message": "(.*)", ), making it loop through all lines until it finds something (in the code I've posted I temporarily changed it to line numbers, trying to speed up the process since it wasn't working).
Also, when trying to load the page, it blocks. As my previous experience with C#'s webclient suggests me, it's probably related to the XMLHttpRequest thing (indeed when I tried to debug it was returning an undefined object).
Thanks in advance for all the help.
var messagelineindex = 14;
var linklineindex = 17;
var response = "";
function loadcommits() {
httpGet("https://api.github.com/repos/trapped/rotmg_svr/commits");
var lines = response.split("\n");
var message = parsemessage(lines[messagelineindex]);
var link = parselink(lines[linklineindex]);
addcommit(//+message+"");
//for (var i = 0; i < numlines; i++) {
// var line = lines[i];
// var commitmessage = parsemessage(line);
// if (commitmessage != "") {
// addcommit(commitmessage);
// break;
// }
//}
}
function parselink(text) {
var regex = /"link": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function parsemessage(text) {
var regex = /"message": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function addcommit(text) {
document.getElementById("commits").innerHTML = document.getElementById("commits").innerHTML + text.toString() + "\n\r";
}
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
}

Related

How do I pull a JSON file that is separate from a RESTFUL API's functions as an authenticated user via an API?

I need to simulate an authenticated user to pull a JSON file. I am using Last.fm's API, but there is currently no method to pull the specific data I want. If I just pull it as plain text in browser, it shows up. However, I want data that is specific to an authenticated user. So, if I login to Last.fm as me, then pull the data, the data is different than if I just pull the data from anywhere.
Basically, the data contained in this file is specific to the user, and as there is no function specifically set to access this file, I don't know how I'd do that....
My function that pulls the current data is listed below:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function getRadio() {
var trackUrls = new Array();
var resValue;
var station;
var radioStation;
var url;
var data;
var neatDisplay;
var resultsDisplay = document.getElementById('result');
var radioTypeInput = document.getElementsByName('radioType');
var queryInput = document.getElementById('query');
var query = queryInput.value;
for (var i = 0, length = radioTypeInput.length; i < length; i++) {
if (radioTypeInput[i].checked) {
station = radioTypeInput[i].value;
break;
}
}
if (station == 1) {
radioStation = "recommended";
} else if (station == 2) {
radioStation = "library";
} else if (station == 3) {
radioStation = "mix";
} else {
radioStation = "music";
};
if (radioStation != "music") {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/user/" + query + "/" + radioStation;
} else {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/music/" + query;
};
console.log(url);
request = createCORSRequest("get", url);
if (request) {
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.responseText);
for (i = 0; i < data.playlist.length; i++) {
trackUrls[i] = data.playlist[i].playlinks[0].url;
}
neatDisplay = trackUrls.join("\n ");
resultsDisplay.innerHTML = neatDisplay;
console.log(neatDisplay.toString());
neatDisplay = neatDisplay.toString();
return neatDisplay.toString();
} else if (request.status == 503) {
resultsDisplay.innerHTML = "Connection Error. The application may be overloaded."
} else {}
};
request.onerror = function() {
document.getElementById("result").innerHTML = "Connection Error. The application may be overloaded. Try again later"
};
request.send();
}
}
Ultimately, this used to pull Spotify links in the resulting data, but now it pulls YouTube. So, the problem only occurs if just pulling the file, without authentication.

update function on ajaxObject

When a button is clicked on the webpage a table of data is displayed. I want to scrape that data but I can't find where it comes from in the website source code.
This is the tag for the button:
<button type="submit" onclick="divChangeStateOn('load-raw-0062294377Amazon.com'); getRaw('0062294377', 'Amazon.com', 'lr-0062294377Amazon.com',this);"style="margin-bottom: 4px; width: 120px; text-align: left;" name="load-raw"><img src='images/workstation.png'/> raw data</button>
I believe that the getRaw function is where the data comes from (I'm not positive about this) so I looked at the javascript code for the getRaw function
function getRaw(asin, store, res, caller)
{ document.getElementById(res).innerHTML = '<p align="center" valign="top"><img align="center" src="phpmy_loading.gif"></p>';
var poststr = "raw=" + encodeURI(asin) +
"&site=" + encodeURI(store);
var updateResults = new ajaxObject(res, 'extra.php', caller);
updateResults.update(poststr);
}
I have been having a hard time finding any documentation about ajaxObject and can't find any information about the update function. What is ajaxObject.update doing and is it possible for me to access the data that appears when the button is clicked?
function divChangeStateOn(divID)
{ var divElem = document.getElementById(divID);
divElem.style.display = 'block';
}
EDIT: The link to the source code view-source:http://www.ranktracer.com/account_workstation.php it might be password protected but I was just using the demo version
EDIT 2:
I am basically trying to write a script that replicates the Ajax http request. This where I am at, it doesn't work and I am especially concerned about where data = uri
x = time.time()
print x
timestamp = datetime.fromtimestamp(x/1000.0)
print timestamp
uri = "raw=0062294377&site=Amazon.com&timestamp="+str(timestamp);
url = "lr-0062294377Amazon.com"
length = str(len(uri))
headers = {'X-Requested-With': 'XMLHttpRequest',
"Content-type": "application/x-www-form-urlencoded",
"Content-length": length,
"Connection" : "close"}
s = Session()
r = s.post(url= url, data= uri, headers= headers)
The entire code for ajaxObject is present in the link you provided. Please let us know what help you are expecting here?
function ajaxObject(layer, url, caller) {
if (caller) {
disableButton(caller, 'disable');
}
var that = this;
var updating = false;
this.callback = function() {}
var LayerID = document.getElementById(layer);
this.update = function(passData) {
if (updating == true) {
return false;
}
updating = true;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX == null) {
alert("Your browser doesn't support AJAX.");
return false
} else {
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4 || AJAX.readyState == "complete") {
if (caller) {
disableButton(caller, 'enable');
}
LayerID.innerHTML = AJAX.responseText;
delete AJAX;
updating = false;
that.callback();
}
}
var timestamp = new Date();
var uri = passData + '&timestamp=' + (timestamp * 1);
AJAX.open("POST", url, true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", uri.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.send(uri);
return true;
}
}
}

Calling data from JSON file using AJAX

I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array

JavaScript: "Syntax error missing } after function body"

Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Ajax Call Only Works the First Time

My JavaScript/ajax code works the first time, but not there after. The GetAttribute element is null when the function is called again. I have try using createElement and AppendChild, but it does the same thing. If I didn't need the getAttribute it would work fine, but I cannot get the function to work with the getAttribute method. Any help would be appreciated.
function ajaxFunction(Picked) {
var getdate = new Date();
if(xmlhttp) {
var Pic1 = document.getElementById("Pic1").getAttribute("name");
var Pic2 = document.getElementById("Pic2").getAttribute("name");
if (Picked === Pic1 ){
var Chosen = Pic1;
var NotChosen = Pic2;
}
else {
var Chosen = Pic2;
var NotChosen = Pic1;
}
xmlhttp.open("POST","choice.php",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("Chosen=" + Chosen + "&NotChosen=" + NotChosen );
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var response = xmlhttp.responseText;
response = response.split("|");
document.getElementById('Pic1').innerHTML = response[0];//New Pic
document.getElementById('Pic2').innerHTML = response[1];
}
else {
alert("Error. Please try again");
}
}
}
Change your if to
if (Picked === Pic1)
By writing if (Picked = Pic1 ), you're assigning Picked to Pic1.

Categories