Consuming API with javascript/jquery

Asked

Viewed 8,087 times

0

I have to consume an IBGE javascript/jquery api

Click here, but I don’t know how to make the filled input data join with the link https://servicodados.ibge.gov.br/api/v1/pesquisas/{researches}. Down with my code

<script>

    var valor1 =  document.getElementById("teste").value;
    $('#botao').click(function() {
    var link ="https://servicodados.ibge.gov.br/api/v1/pesquisas/"+valor1;
    $.ajax({
        url: link,
        type: 'GET',
        dataType: 'json',

    })
    .done(function() {
        console.log("success");
        console.log(valor1);
        document.getElementById("demo").innerHTML = valor1;
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
    });


</script>
  • The way you did, what a mistake?

  • You try to capture the code with var valor = $("#idDoCampo").val() and put it the way you did in your research

2 answers

2


You are capturing the value of the field at the wrong time when it has not yet been filled Move the assignment of var valor1 = document.getElementById("teste").value; to the scope of your button click event.

$('#botao').click(function() {
  var valor1 = document.getElementById("teste").value;
  var link = "https://servicodados.ibge.gov.br/api/v1/pesquisas/" + valor1;
  $.ajax({
      url: link,
      type: 'GET',
      dataType: 'json',

    })
    .done(function() {
      console.log("success");
      console.log(valor1);
      document.getElementById("demo").innerHTML = valor1;
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });
});

1

$.ajax({
   type: 'GET',
   url: suaUrlAqui
   success: function(data) {
       // O que pretende fazer aqui.
       //ex:
       var pessoa = JSON.parse(data);
       document.getElementById("CPF").value= pessoa.pessoa[0].CPF;
  }
});

You can take the answer in the Success and assign it to a variable and use that variable within the Success function.

Browser other questions tagged

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