Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda