Request sent more than once when selecting a form field

0

When I select some specific field of a form, I trigger a request to load some essential information to complete the form, but when selecting a form field it triggers 3, 4 requests and this causes my data of an option for example get duplicates inside the form.

// requisição
$('body').on('click', '#cmbContrato', function () {

    contrato = $("#cmbContrato").val();

    $.ajax({
        type: 'GET',
        url: 'ProtocoloExterno/GetItensContrato',
        data: { dado: contrato },
        dataType: 'JSON',
        success: function (dados) {
            if (dados !== 0) {

                   var selectbox = $('#cmbItensContrato');

                    $.each(dados, function (i, d) {
                        $('<option>').val(d.id).text(d.value).appendTo(selectbox);
                    });
                }
            } 
        },
        error: function () {
            console.log("Erro ao enviar AJAX");
        }
    });

});


// metodo em c# asp.net mvc



[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public JsonResult GetItensContrato()
{
    List<object> resultado = new List<object>();
    long numeroContrato = 0;
    if (Request.QueryString["dado"] != "")
    {
         numeroContrato = long.Parse(Request.QueryString["dado"]);
    }

    var infosContrato = db.ItemContrato.Where(c => c.ContratoId == numeroContrato.ToString()).Select(c => c.ItemRCid);

    foreach(int itensContrato in infosContrato)
    {
         resultado.Add(new { id = itensContrato, value = itensContrato });
    }
        return Json(resultado, JsonRequestBehavior.AllowGet);
  }

How can I solve this problem?

    
asked by anonymous 11.04.2018 / 13:41

1 answer

1

You are binding in the wrong event, as you defined it, every time the user clicks on #cmbContrato you fire the ajax request.

And as noted by @Barbetta, you're always adding elements to your #cmdItensContrato . So in your case besides the wrong event you are mistakenly interpreting the result obtained and assigning the cause as solely related to the multiple shots of the ajax request.

Switch to change

$('body').on('change', '#cmbContrato', function() {
  var contrato = $("#cmbContrato").val();

  $.ajax({
    type: 'GET',
    url: 'ProtocoloExterno/GetItensContrato',
    data: {
      dado: contrato
    },
    dataType: 'JSON',
    success: function(dados) {
      if (dados !== 0) {

        var selectbox = $('#cmbItensContrato');
         
        //Removendo os itens presentes no segundo combobox;
        selectbox.find('option').remove();        

        $.each(dados, function(i, d) {
          $('<option>').val(d.id).text(d.value).appendTo(selectbox);
        });
      }
    },
    error: function() {
      console.log("Erro ao enviar AJAX");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><body><selectid="cmbContrato">
      <option value="1">Contrato 1</option>
      <option value="2">Contrato 2</option>
      <option value="3">Contrato 3</option>
      <option value="4">Contrato 4</option>
  </select>
</body>

</html>
    
11.04.2018 / 14:24