Reputation: 431
I have below HTML page which I land on after successful authentication. In its body, I get access_token value.
<html>
<head>
<title>Authorization successful</title>
</head>
<body>
<p>Welcome. You are authorized to access the page.</p>
<p>access_token: {{ access_token }}</p>
<p>token_type: {{ token_type }}</p>
<form method="POST" action="/protected_hi" >
<button type="submit" id="protectedApiButton">Protected API</button>
</form>
<script src="ajax.js"></script>
</body>
</html>
The page has a button named "Protected API" on which ajax.js script it registers. How can I get the access_token variable's value in my ajax.js script?
let protectedApiButton = document.getElementById('protectedApiButton');
protectedApiButton.addEventListener('click', buttonClickHandler)
function buttonClickHandler() {
var myAttribute = <------------- how to assign access_token value from html template to here?
console.log(myAttribute);
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://dummy.restapiexample.com/api/v1/create', false);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onprogress = function(){
console.log('On progress');
}
xhr.onload = function () {
if(this.status === 200){
console.log(this.responseText)
}
else{
console.log("Some error occurred")
}
}
params = `{"name":"ravi","age":"43"}`;
xhr.send(params);
}
Upvotes: 1
Views: 271
Reputation: 2005
Add the input with the type of hidden to store the access token.
<input type="hidden" id="access_token" value="token-goes-here" />
Then retrieve the value from access_token
in the buttonClickHandler()
:
function buttonClickHandler() {
var myAttribute = document.getElementById('access_token').value;
...
}
Upvotes: 1