How to make a POST request with Javascript form

Asked

Viewed 387 times

0

Hello! I’m trying to make a request through Javascript, but I’m not getting it.

I need to pick up the e-mail through a form and send this amount for the request, type application/x-www-form-urlencoded

On the Postman I put on the body the following way

key: email value: ["meuemail@com"]

How do I take this form input value, turn it into this format I need and submit the request?

My JS code looks like this:

var btn = document.getElementById("Bsubmit");
var request = new XMLHttpRequest();
request.open('POST', '/request', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');


btn.onclick = function() {
 request.send();
}

1 answer

1


Here is an example:

// Exemplo de requisição POST
var ajax = new XMLHttpRequest();
var email = document.getElementById("txtEmail").value; //Input texto com id "txtEmail"

// Seta tipo de requisição: Post e a URL da API
ajax.open("POST", "minha-url-api", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Seta paramêtros da requisição e envia a requisição
ajax.send("email=" + email);

// Cria um evento para receber o retorno.
ajax.onreadystatechange = function() {
  
  // Caso o state seja 4 e o http.status for 200, é porque a requisiçõe deu certo.
	if (ajax.readyState == 4 && ajax.status == 200) {
    
		var data = ajax.responseText;
		
    // Retorno do Ajax
		console.log(data);
	}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.