How to send a JSON object in a POST request with ajax?

Asked

Viewed 2,367 times

1

I need to send a json object with ajax to an external API but cannot include variables instead of static values

var numSGPE = document.getElementById('numSGPE').value
var setor = document.getElementById('setor').value
var subTipo = document.getElementById('subTipo').value
var tipo = document.getElementById('subTipo').value

$.ajax({
    url : "http://localhost:8080/NumDocumentos",
    method : "POST",
    contentType : 'application/json',
    dataType : 'json',
    data : '{"especie":""+tipo+"", "gerencia":""+setor+"", "numSGPE":""+numSGPE+""}'
    }).done(function(res) {
      console.log(res)
    })


If you change the variables (tipo, setor, numSGPE) by static values works well, but that send the values as they are in these variables.

2 answers

0

Although the @Lucas Bittencourt response works, a simpler and more flexible option is to use the method JSON.stringify().

The method JSON.stringify() converts values into javascript for a String JSON.

const dadosForm = {
    numSGPE: document.getElementById('numSGPE').value,
    gerencia: document.getElementById('setor').value,
    especie: document.getElementById('subTipo').value
};

$.ajax({
    url : "http://localhost:8080/NumDocumentos",
    method : "POST",
    contentType : 'application/json',
    dataType : 'json',
    data : JSON.stringify(dadosForm)
}).done(function(res) {
    console.log(res)
});

0


Hello,

Turns out you’re using simple quotes ' to open and close your string, so you could do it this way:

data : '{"especie":"' + tipo + '", "gerencia":"' + setor + '", "numSGPE":"' + numSGPE + '"}';

But I strongly recommend using the template strings, that would look like this:

data : `{"especie":"${tipo}", "gerencia":"${setor}", "numSGPE":"${numSGPE}"}';
  • so I’m not using any Angular or React framework, it’s a simple html that has some inputs and a javascript that makes this request at the click of the button, hence these strig templates do not work

  • the template strings is Javascript :)

  • 1

    I’m sorry I thought javascript vanilla didn’t recognize ${} this format. It worked great Thanks.

Browser other questions tagged

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