Consume API with javascript / jquery

0

I have to consume an api in javascript / jquery from IBGE

Click here , but I do not know how to make the data of the input filled together with the link link {searches}. Below 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>
    
asked by anonymous 02.05.2018 / 19:58

2 answers

1

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 the click event of your button.

$('#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");
    });
});
    
02.05.2018 / 21:01
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 pick up the answer in success and assign it to a variable and use that variable within the function of success.

    
02.05.2018 / 20:46