Request sent more than once when selecting a form field

Asked

Viewed 110 times

0

When I select a specific field from a form, I trigger a request to load some essential information to complete the form, only when selecting a form field it fires 3, 4 requests and this causes my data from an option for example to be duplicated within 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 to solve this problem?

  • managed to solve?

  • I managed to solve yes, but it was the outside call... but it keeps coming replicated @Leandroangelo

  • In json do they come duplicated? or are they just adding to the ones already on the screen? you added the remove() of my edited reply?

  • in Json they come duplicated, the error is in the return of Entity

  • You say duplicated, because it’s passing the same value to the id and the value? In this passage: resultado.Add(new { id = itensContrato, value = itensContrato });

  • No, that the return that comes from Entity sends twice the same record

  • Have you ever made the same query at the bank? Did you actually have duplicate records there?

  • No bro, I already did yes, it is return stick of the Entity json

Show 3 more comments

1 answer

1

You are doing the bind on the wrong event, the way you set it, every time the user clicks on #cmbContrato you trigger the ajax request.

And as noted by @Barbetta, you’re always adding elements to your #cmdItensContrato. So in your case beyond the wrong event you are misinterpreting the obtained result and assigning the cause as only related to the multiple shots of the ajax request.

Switch to the 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>
  <select id="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>

  • even so it continues to send the request twice

  • not have, id is unique and blah blah

  • If he’s still firing twice, it’s because you’re doing the bind more than once. Look in your code to see if you have another $('body').on('change', '#cmbContrato'

  • No, it turns out that all Binds are being fired more than once and are being called only once

  • Is your js written directly on the page or view or being included as an exeterno file? Make sure you don’t mind it in the master and view or by declaring it in the Bundle and importing it again later. And anyway, you need to change the click for change This will already cause the ajax to fire twice.

  • I don’t know if it can be this.. if I’m wrong I remove the comment.. but I didn’t see it in his code, it wiping the select before filling it again with the data coming from the server. maybe that’s it

  • @Leandroangelo that I thought, I’m calling him in a modal, whose modal and page that calls the modal I’m calling the same file..

  • And look at the @Barbetta comment, you’re not cleaning the #cmbItensContrato before adding the new items, they will end up stacking.

  • @Leandroangelo, even just coming a request, he kind of duplicates the data... I don’t know if it’s Json’s return that’s wrong

  • @gabrielfalieri, see my last issue to reply.

Show 5 more comments

Browser other questions tagged

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