Multiple form ajax request, with javascript function

0

I'm having trouble sending forms correctly, I have several forms, each with its id, and a function that 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>
    
asked by anonymous 12.01.2018 / 19:55

2 answers

1

You can also do it 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');
        }
    });

});

So, it will only get the inputs of the form in question, regardless of the other X's that are on the same page

    
13.01.2018 / 07:49
0

I found the error that I presented myself here, I'll put the answer for future reference:

The names of the inputs are all the same, when selecting a random input and submitting the form, it was selected, selecting another input caused the conflict. To solve clean all the 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.

    
13.01.2018 / 03:22