Home > Mobile >  How can I pass the value of a javascript variable to django?
How can I pass the value of a javascript variable to django?

Time:12-06

How can I send the value of "const token" to django?

function getToken() {
    PagSeguroDirectPayment.createCardToken({
        cardNumber: '4111111111111111', 
        brand: 'visa', 
        cvv: '123', 
        expirationMonth: '12', 
        expirationYear: '2030', 
        success: function(response) {
            const token = response.card.token;
        },
        error: function(response) {
            
        },
        complete: function(response) {
             
        }
     });
}

the getToken() function is being executed like this:

 <form action="{% url 'payments' %}" method="POST" onsubmit="getToken()">

I had tried to pass the Token value to a hidden input, and then I tried to get that value in django as shown below, but the input takes a while to receive the value and is already sent to the other page immediately. That way I would need to make sure that the input has the token value to let it forward to the other page

success: function(response) {
            document.getElementById('cardToken').value = response.card.token;
        },

CodePudding user response:

Assuming the token value isn't sensitive data, just push it to a cookie using JavaScript and then retrieve the cookie using Django:

JavaScript:

const token = response.card.token;
document.cookie = "someToken="   token;

Django:

request.COOKIES.get('someToken') 
  • Related