Ajax request from multiple Forms, with javascript function

Asked

Viewed 579 times

0

I’m having trouble sending the forms correctly, I have several forms, each with its id, and a function I call on all forms:

<script>
  function enviaForm(id){
    $(id).submit(function(){

      var camp1 = $("input[name='a2']:checked").val();     

      $.ajax({
        type: "GET",
        url: "proc_update_teste.php",
         data: {
              'campo1': camp1
            },
        success: function(result){
              camp1 = $("input[name='a2']:checked").val('');
              var view = $('#resultSend').html(result);
            }
      });      
      return false;
    });

  }
</script>
<form id="q1">
  <h1 class="flow-text white-text">Question 1</h1>
  <input type="hidden" name="question1">
  <p class="white-text">What is your father's last name?</p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q1a" value="answer1a"/>
    <label for="q1a">a. His last name Silva</label>
  </p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q1b" value="answer1b" />
    <label for="q1b">b. My father last name is Silva</label>
  </p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q1c"  value="answer1c"/>
    <label for="q1c">c. His last name is Silva</label>
  </p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q1d" value="answer1d" />
    <label for="q1d">d. My father is last name Silva</label>
  </p>
  <button class="btn" onclick="enviaForm(q1)">RESPONDER</button>
</form>
<hr>
<form id="q2">
  <h1 class="flow-text white-text">Question 2</h1>
  <input type="hidden" name="question2">
  <p class="white-text">2.  What do you do for a living?</p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q2a" value="answer2a"/>
    <label for="q2a">a. I am a doctor.</label>
  </p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q2b" value="answer2b"/>
    <label for="q2b">b. I watch tv</label>
  </p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q2c"  value="answer2c"/>
    <label for="q2c">c. I´m teacher.</label>
  </p>
  <p>
    <input class="with-gap" name="a2" type="radio" id="q2d" value="answer2d"/>
    <label for="q2d">d. I live in São Paulo.</label>
  </p>
  <button class="btn" onclick="enviaForm(q2)">RESPONDER</button>
</form>
<hr>
  • what the difficulty?

  • When I click the second button takes the data from the first form, I don’t know if this is how you pass the id to the function, when I call it on the button

2 answers

1

You can also do this way

    // monitora todos os formularios que NÃO contenha a classe "noajax" (formularios com essa classe não são enviados fica ajax)
$('form:not(.noajax)').on("submit", function(ev){
    ev.preventDefault();
    // url base para onde irá as requisições ajax
    var BASE_URL = 'seusite.com/ajax/'
    // seleciona o botão de submit
    var botao = $(this).find('input[type="submit"]');
    // salva o value do botão para voltar o texto original após a resposta da requisição
    var textBotao = botao.val();

    // desabilita o botão para evitar multiplos envio
    botao.prop("disabled", true).val("Carregando...").css('opacity', '0.5');

    // pega o endereço que o formulario vai ser enviado 
    var action = $(this).attr("action");

    // uma verificação basica para ter certeza que colocou um action
    if(action == undefined || '' == action)
        return alert("Não foi possível processar sua requisição, coloque um action");

    $.ajax({
        url: BASE_URL+action+".php",
        data: $(this).serialize(),
        type: "POST",
        success: function(result){
            // coloca em algum lugar o resultado 
            $("#erroslist").html(result);
            botao.prop("disabled", false).val(textBotao).css('opacity', '1');
        },
        error: function(){
            botao.prop("disabled", false).val(textBotao).css('opacity', '1');
        }
    });

});

Thus, it will take only the inputs of the form in question, independent of the other X that are on the same page

0

I found the mistake that I myself presented here, I will put the answer to future consultations:

The input numbers are all the same, when selecting a random input and submitting the form, the same was selected, when selecting another input caused conflict. To resolve clean all inputs when submitting any form with the code:

camp1 = $("input[name='cbn']:checked").prop('checked',false);

This allows only one input to be selected at a time, correctly sending the request.

Browser other questions tagged

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