Consume API (JSON) in form fields, how to do?

Asked

Viewed 6,191 times

3

Hello, my fellow programmers.

I would like a help. I have to use in a project the API that contains the Table Fipe data in JSON format (http://deividfortuna.github.io/fipe/).

I want my form to have four fields: Brand, Model, Year and Value.

When I select the Brand of the Car (Bike or Truck), the Model field will show the items related to that brand. When selecting the car model, the third field with the year will open. Finally, when selecting the year, the last field shall display the value of this vehicle.

I haven’t been able to do anything so far, despite attempts. I won’t even expose my code because I need help from scratch. This is important because I need to implement this function in a vehicle classified design.

If anyone can help me, I’d be grateful.

  • 1

    post the code of what you have already tried in it. It may be halfway walking to help you achieve the intended.

  • You’re basically asking someone to do their job.

  • No, I don’t want anyone doing my job. I would just like a "step-by-step" to better understand the process and analyze what I was doing right or where I went wrong.

2 answers

3

You can do something like this to consume the API, using jQuery, the combo dynamic part is up to you, because it requires time and dedication to development, I believe this is your job. But luckily, you can find some functional examples already chewed through the Internet. Look for terms of "how dynamically popular combobox". This site have an example of this kind of operation, analyze the source code it has the implementation for you:

HTML:

<form method="post" action="/enviar" name="formul">
    <div id="form"></div>
</form> 

Javascript:

$.getJSON('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas', function(data) {

    var select = '<select name="modelos">\
                  <option>Selecione...</option>';
    for (var i in data) {

         select += '<option value="'+data[i].codigo +'">'+ data[i].nome + '</option>';

    }
    select += '</select>';
    $('#form').html(select);

});

See working here

  • 1

    Perfect your answer. I was sinning at the time of implementing in the form, to open the fields I wish to return information. So it became clearer. Thank you.

  • Hi @Marcospaulo, if my reply helped you, mark it that it served your purpose. Thank you!

3

Follow an option using Javascript only (no dependency to jQuery).

var form = {};
form.fipe = document.getElementById("fipe");
form.marcas = document.getElementById("marcas");
form.modelos = document.getElementById("modelos");
form.anos = document.getElementById("anos");
form.fieldset = document.getElementById("veiculo");

form.veiculo = {};
form.veiculo.valor = document.getElementById("veiculo_valor");
form.veiculo.marca = document.getElementById("veiculo_marca");
form.veiculo.modelo = document.getElementById("veiculo_modelo");
form.veiculo.anomodelo = document.getElementById("veiculo_anomodelo");
form.veiculo.combustivel = document.getElementById("veiculo_combustivel");
form.veiculo.codigofipe = document.getElementById("veiculo_codigofipe");
form.veiculo.mesreferencia = document.getElementById("veiculo_mesreferencia");
form.veiculo.tipoveiculo = document.getElementById("veiculo_tipoveiculo");
form.veiculo.siglacombustivel = document.getElementById("veiculo_siglacombustivel");

var getJSON = function (url, sucesso, erro) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.open("GET", url, true);
  httpRequest.responseType = "json";
  httpRequest.addEventListener("readystatechange", function (event) {
    if (httpRequest.readyState == 4) {
      if (httpRequest.status == 200) {
        if (sucesso) sucesso(httpRequest.response);
      } else {
        if (erro) erro(httpRequest.status, httpRequest.statusText);
      }
    }
  });

  httpRequest.send();
}

var getMarcas = function () {
  var url = 'https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/';
  getJSON('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas', function (marcas) {

    form.marcas.innerHTML = "";
    form.marcas.disabled = null;

    var selectOption = document.createElement("option");
    selectOption.textContent = "Selecione...";
    selectOption.value = "";
    form.anos.appendChild(selectOption);

    marcas.forEach(function (marca, indce) {
      var optionMarca = document.createElement("option");
      optionMarca.textContent = marca.nome;
      optionMarca.value = marca.codigo;
      form.marcas.appendChild(optionMarca);
    });   

  }, function (errorCode, errorText) {

  });
}

var getModelos = function () {
  var url = 'https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + form.marcas.value + '/modelos';
  var selectOption = form.modelos.querySelector("option");
  selectOption.textContent = "Carregando Marcas";

  getJSON(url, function (modelos) {

    form.modelos.innerHTML = "";
    form.modelos.disabled = null;

    var optionModelo = document.createElement("option");
    optionModelo.textContent = "Selecione...";
    optionModelo.value = "";
    form.modelos.appendChild(optionModelo);

    var optionAno = document.createElement("option");
    optionAno.textContent = "Selecione um Modelo";
    optionAno.value = "";
    form.anos.appendChild(optionAno);

    modelos.modelos.forEach(function (modelo, indce) {
      var optionModelo = document.createElement("option");
      optionModelo.textContent = modelo.nome;
      optionModelo.value = modelo.codigo;
      form.modelos.appendChild(optionModelo);
    });   

  }, function (errorCode, errorText) {

  });
}

var getAnos = function () {
  var url = 'https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + form.marcas.value + '/modelos/' + form.modelos.value + '/anos';
  var selectOption = form.anos.querySelector("option");
  selectOption.textContent = "Carregando Anos";

  getJSON(url, function (anos) {

    form.anos.innerHTML = "";
    form.anos.disabled = null;

    var optionAno = document.createElement("option");
    optionAno.textContent = "Selecione...";
    optionAno.value = "";
    form.anos.appendChild(optionAno);

    anos.forEach(function (ano, indce) {
      var optionAno = document.createElement("option");
      optionAno.textContent = ano.nome;
      optionAno.value = ano.codigo;
      form.anos.appendChild(optionAno);
    });   

  }, function (errorCode, errorText) {

  });
}

var getVeiculo = function () {
  var url = 'https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + form.marcas.value + '/modelos/' + form.modelos.value + '/anos/' + form.anos.value;  

  getJSON(url, function (veiculo) {
    form.fieldset.disabled = "";
    form.veiculo.valor.value = veiculo.Valor;
    form.veiculo.marca.value = veiculo.Marca;
    form.veiculo.modelo.value = veiculo.Modelo;
    form.veiculo.anomodelo.value = veiculo.AnoModelo;
    form.veiculo.combustivel.value = veiculo.Combustivel;
    form.veiculo.codigofipe.value = veiculo.CodigoFipe;
    form.veiculo.mesreferencia.value = veiculo.MesReferencia;
    form.veiculo.tipoveiculo.value = veiculo.TipoVeiculo;
    form.veiculo.siglacombustivel.value = veiculo.SiglaCombustivel;
  }, function (errorCode, errorText) {

  });
}

form.marcas.addEventListener("change", function (event) {    
  form.modelos.disabled = "disabled";
  form.anos.disabled = "disabled";
  form.fieldset.disabled = "disabled";

  form.anos.innerHTML = "";
  var optionAno = document.createElement("option");
  optionAno.textContent = "Selecione um Modelo";
  optionAno.value = "";
  form.anos.appendChild(optionAno);

  if (form.marcas.value) {
    getModelos();
  } else {
    form.modelos.innerHTML = "";
    var selectOption = document.createElement("option");
    selectOption.textContent = "Selecione uma Marca";
    selectOption.value = "";
    form.modelos.appendChild(selectOption);
  }
});

form.modelos.addEventListener("change", function (event) {    
  form.anos.disabled = "disabled";
  form.fieldset.disabled = "disabled";

  if (form.modelos.value) {
    getAnos();
  } else {
    form.anos.innerHTML = "";
    var optionAno = document.createElement("option");
    optionAno.textContent = "Selecione um Modelo";
    optionAno.value = "";
    form.anos.appendChild(optionAno);
  }
});

form.anos.addEventListener("change", function (event) {
  form.fieldset.disabled = "disabled";

  if (form.anos.value) {
    form.fieldset.disabled = "disabled";

    getVeiculo();
  } else {

  }
});

getMarcas();
fieldset {
  width: 280px;  
}

fieldset div { 
  clear: both;
}
fieldset div label {
  float: right;
}
<form id="fipe" method="post" action="enviar" >
  <div>
    <select id="marcas" name="marcas" disabled="disabled">
      <option>Carregando Marcas</option>
    </select>
  </div>
  <div>
    <select id="modelos" name="modelos" disabled="disabled">
      <option>Selecione uma Marca</option>
    </select>
  </div>
  <div>
    <select id="anos" name="anos" disabled="disabled">
      <option>Selecione um Modelo</option>
    </select>
  </div>
  <fieldset id="veiculo" disabled="disabled">
    <div>
      <label>
        Valor:
        <input id="veiculo_valor" name="veiculo.valor" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Marca:
        <input id="veiculo_marca" name="veiculo.marca" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Modelo:
        <input id="veiculo_modelo" name="veiculo.modelo" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Ano Modelo:
        <input id="veiculo_anomodelo" name="veiculo.anomodelo" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Combustivel:
        <input id="veiculo_combustivel" name="veiculo.combustivel" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Codigo Fipe:
        <input id="veiculo_codigofipe" name="veiculo.codigofipe" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Mes Referencia:
        <input id="veiculo_mesreferencia" name="veiculo.mesreferencia" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Tipo Veiculo:
        <input id="veiculo_tipoveiculo" name="veiculo.tipoveiculo" type="text" readonly>
      </label>
    </div>
    <div>
      <label>
        Sigla Combustivel:
        <input id="veiculo_siglacombustivel" name="veiculo.siglacombustivel" type="text" readonly>
      </label>
    </div>
  </fieldset>  
</form>

  • Very good code model. I will study your lines, because with me it works like this: I need to see to understand. It was very clear your answer. Thank you very much.

Browser other questions tagged

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