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.