I'm fairly new to API's and JavaScript so I'm not sure what wrong I'm doing here, please find the details below for the problem which I'm facing
Objective - Get Jenkins Details On A Webpage
As a part of my objective, I'm trying to make a web page from where I can trigger a Jenkins job and get the info of the build displayed on the webpage. As one of the part of the objective I want to trigger a Jenkins job from a button on my webpage.
Issue -
I created following script to do the operation -
<script>
function RunJenkinsJob() {
var xhr = new XMLHttpRequest();
xhr.open("POST", http://admin:114a2eae5e09d93b6ee831f248892ac581#localhost:8080/job/New_Test/build?token=Datacreation, true);
xhr.setRequestHeader('Content-Type', 'application/json');
}));
}
</script>
<head>
<style>body{background-color:#d0e4fe;}h1{color:orange;text-align:center;}p{font-family:"Times New Roman";font-size:20px;}</style>
</head>
<body>
<h1>Check Jenkins Job Build</h1>
<button type="button" onclick="RunJenkinsJob();"> Run Jenkins Job! </button>
</body>
</html>
However when I try to click this button nothing is happening, upon accessing this URL directly from browser I'm asked to provide username and password and then after refreshing new build gets triggered automatically.
Question
How to provide authentication for Jenkins in this JavaScript method so that on clicking the Button New Job can be triggered and also if I can get some pointers on how to extract the information about the build that also would be very useful.
System Details
OS - Windows
Jenkins Version - 2.235.1
-- Update 1 -
Please find the updated details below -
<!DOCTYPE html>
<html>
<script>
function RunJenkinsJob() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://admin:114a2eae5e09d93b6ee831f248892ac581#localhost:8080/job/New_Test/build?token=Datacreation", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
document.write(xhr.status);
}
</script>
<head>
<style>body{background-color:#d0e4fe;}h1{color:orange;text-align:center;}p{font-family:"Times New Roman";font-size:20px;}</style>
</head>
<body>
<h1>Check Jenkins Job Build</h1>
<button type="button" onclick="RunJenkinsJob();"> Run Jenkins Job! </button>
</body>
</html>
The following code worked for me.
Put this into your run jenkins job function. This would help debug if it cycles through all the 4 state changes and status it recieves.
var xhr = new XMLHttprequest();
var authorizationbasic = window.btoa("username:token");
xhr.onreadystatechange = function() {
if(this.readyState == 4)
{
console.log(this.status);
}
};
xhr.open("POST", "http://admin:114a2eae5e09d93b6ee831f248892ac581#localhost:8080/job/New_Test/build?token=Datacreation", true);
xhr.setRequestHeader('Authorization','Basic ' + authorizationbasic)
xhr.send();
If you still get status as 0 then you can check the CORS Filter setting in your jenkins installation.
Related
In my application I made some computing server side with a Javascript interpreter. I'd like to take advantage from F12 debug engine in my browser chroome to let the user debug his scripts. To do that a generare a new page and open it in a new window
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/test/tipoManufatto", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var new_window = window.open(null, '');
new_window.document.write(this.responseText);
}
};
xhttp.send(JSON.stringify($scope.tc.selected));
the page is generated correctly and the server side generated scripts runs fine but if get into F12 tools
I cannot see my script in the source tab therefore I cannot set any breakpoints.
Is there a better way to open a dynamically generated page in a new window? I need to generate the page from the back-end with a POST verb in order to send some data.
Here is what my network tabs looks like
I have locally recreated an embedded-script example from the W3Schools site, but it does not work properly. It executes, creating the expected HTML page, but the onclick-activated XHR function does not alter the innerHTML content as expected. Here is the original code from the relevant page (https://www.w3schools.com/xml/tryit.asp?filename=tryxml_httprequest):
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
I've tried several things:
I created a local text file with the same name as the one being opened in the sample script, and put it in the same directory. Page loaded with button, nothing happened when it was clicked.
I added "tracers" to the script in the form of alerts to confirm the script's progression:
function loadXMLDoc() {
alert("main function successfully called");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
alert("onreadystatechange function successfully called");
alert("readyState: " + this.readyState + " " + "status: " + this.status);
if (this.readyState == 4 && this.status == 200) {
alert("readyState/status function successfully called");
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
When executed, the first two alerts appeared as expected. The third appeared twice, reflecting a change in readyState from 1 to 4, but the status remained 0 in both alerts. The fourth "tracer" alert never appeared.
I altered the final conditional to allow for "status == 0", and the fourth alert appeared, and the button disappeared...replaced by nothing.
Just to be sure, I changed it so that the string "hello world" was directly added to the innerHTML, which worked.
I tried the same variants on a different workstation (both were running Ubuntu Linux btw, and I executed the code with both Firefox and Chromium).
Obviously, the responseText is coming up empty. And presumably this is because the request failed, as evidenced by the status remaining 0 instead of changing to 200.
It would be bad enough if I couldn't get this simple code to work, but here's the hair-tearing, teeth-gnashing part: I ran this same code sample a couple of days before, and it executed flawlessly. Furthermore, I had written a much more complicated script employing my new-found knowledge of xhr to load much larger files, store their contents in variables and perform .searchs on them, also without any problems. I was in the process of elaborating the code when it failed, and at first I thought I'd made a change that "broke" it. But as I rolled it back to more and more "primitive" versions - versions I knew had worked - I discovered xhr no longer worked at all, as corroborated by formerly executable tutorial code no longer working, either.
I don't remember if there was an interim update of Firefox or Chromium that might have affected things, but that seems like a pretty weak possibility.
What am I missing?
Thanks in advance,
Rob
I am trying to create a web page that opens another web page when you click the "Try It" button, and then counts the number of characters in that webpage. Right now, this web page successfully opens the web page I ask it to open, but the length of the web page in characters is "undefined". I do not want to get rid of the XMLHttpRequest or the line of code below it, because I am planning to expand this webpage to enable it to parse the webpage by certain specific keywords later. Here is the code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
window.open("https://www.gutenberg.org/files/1065/1065-h/1065-h.htm");
var req = new XMLHttpRequest();
req.open('GET', 'https://www.gutenberg.org/files/1065/1065-h/1065-h.htm', false);
alert(req.length);
}
</script>
</body>
</html>
Any assistance that anyone can provide me would be greatly appreciated. Have a nice day.
First of all you need a flag header in the remote server that allow your url to make XMLHttpRequests.
Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: yoururl.com
Another problem is that https version has a redirect to http version, then you could have problems if you are executing this from a https site, because of "mixed content" behaviour of client's browsers. Also synchronous XMLHttpRequest (false flag) is deprecated or going to be deprecated soon https://xhr.spec.whatwg.org/ .
If you perform this in the same domain (http gutenberg) it works. You should try executing this in your http server, and looking the console expecting not to have Access-Control-Allow-Origin restriction.
var req = new XMLHttpRequest();
req.open('GET', 'http://www.gutenberg.org/files/1065/1065-h/1065-h.htm', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
console.log(req.responseText);
else
console.log("Error loading page\n");
}
};
req.send(null)
I have started working my way through the AJAX tutorial on the W3Schools website and my first example won't even run. Why won't this run please? It opens up in the browser but nothing happens when I click the button.
The tutorial URL;
https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_ie
Here is my HTML page that I created in Notepad++
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onClick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6 and IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
I run the HTML page by selecting Run >> chrome in Notepad++ (but tried Firefox and IE too). The ajax_info.txt file is in the same location as the HTML file. Here is its contents;
AJAX is not a programming language.
AJAX is a technique for accessing web servers from a web page.
AJAX stands for Asyncronous JavaScript And XML.
you must change xhhtp.onreadystatechange instead of xhttp.onreadystatechange and xhhtp.send(); instead of xhttp.send();
function loadDoc() {
debugger;
var xhhtp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhhtp = new XMLHttpRequest();
} else {
// code for IE6 and IE5
xhhtp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhhtp.open("GET", "ajax_info.txt", true);
xhhtp.send();
}
Because of the typo xhhtp instead of xhttp.
You should read up on CORS. For example:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Your can see your code working if you run a local web server, which serves the html file in question (keep the txt file in the same directory as the html file).
If you are on a mac, an easy way to run a local web server is to run the following code from where your html file is:
python -m SimpleHTTPServer 8001
then in your browser go to
http://localhost:8001/yourhtmlfile.html
Since you mentioned notepad++, seems you are not on mac, but some light googling will give you a similar setting for windows.
Thanks everyone. I installed Apache and set port to 7777 (because already had IIS on port 80) and placed files in htdocs location of apache and used the url http://localhost:7777/htdocslocation/FirstAJAXExample.html and it worked.
At some point my webpage is changing its location.href, resulting in the browser navigating to another page.
I would like to do a XHR POST request just before changing the page.
I would rather not wait for this XHR request completion, because not receiving 100% of the requests is OK but speed is paramount.
I tried this code, however the XHR request is NOT send by Firefox/Chrome, because of the location.href change right after.
<html>
<head></<head>
<body>
This is page test1.htm<br>
<input type="button" value="Go!" onclick="go();">
<script>
function go() {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { /* Do nothing */ };
xhr.open('POST', '/cgi-bin/hb.exe?action=remoteapppost', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('action=remoteapppost&id=TEST');
// ==> this XHR request is NOT sent because of the following line:
location.href = "test2.htm";
}
</script>
</body>
</html>
If I do a breakpoint or move the location.href = "..."; inside the callback, everything is working fine (of course).
Any idea on how to send a XHR request just before leaving a webpage?
You want to use a combination of the beforeunload event and the new navigator.sendBeacon() API that's designed to not block navigation.