Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
how to pass variable from html to ajax/javascript

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);    
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
  ...
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!