Why does 'jQuery' run twice?

0

js where I have 'jQuery', the problem is that I am executed twice. Someone can explain to me what is due and how to solve it please. Annex the jQuery ...

    $(document).ready(function(){
       $("#botonExportar").click(function(){
          var data = $("#producto").val();
          alert('productoBuscado='+data);
          $.post("registrosExportaciones.php",{producto:data}, function(respuesta){
               alert('todo bien..'+respuesta);
          });
      });
  });

Here is the html ...

     <div class="" align="right">
     <form id="registrarExportacion" action="./FPDF/generarReporte.php" method="POST" target="_blank">
       <input type="hidden" name="tipoReporte" value="detecciones">
       <input type="hidden" name="producto" id="productoBuscado" value="$producto">
       <button type="submit" id="botonExportar" class="btn btn-default btn-md exportar" name="button" style="background-color:red !important; margin-top:1%;">Exportar</button>
     </form>
   </div>
    
asked by Alberto Rojas 21.12.2016 в 01:23
source

4 answers

2

you are sending the form 2 times, one through Ajax and another through the form itself.

Modify this line

<button type="submit" id="botonExportar" class="btn btn-default btn-md exportar" name="button" style="background-color:red !important; margin-top:1%;">Exportar</button>

For this

<button type="button" id="botonExportar" class="btn btn-default btn-md exportar" name="button" style="background-color:red !important; margin-top:1%;">Exportar</button>

What we change is the type of button from "submit" to "button". The type "submit" sends the form but there is a javascript event associated with the same button.

    
answered by 21.12.2016 в 13:03
1

I did tests and the JQuery is not running twice. The data is being sent twice:

  • With <form ... action="./FPDF/generarReporte.php">
  • With $.post("registrosExportaciones.php"...)

Can you recreate it in link ?

Test: link

    
answered by 21.12.2016 в 02:01
0

One of the reasons why this happens is because you are adding the jQuery CDN and your external file Js:

<script src="https://code.jquery.com/jquery-3.3.1.js" type="text/javascript"></script>
<script src="index.js" type="text/javascript"></script>

In this way there are conflicts between the framework and vanillaJS. If you are going to use jQuery, the version does not matter, you should not insert .Js files, so you just have to leave:

    <script src="https://code.jquery.com/jquery-3.3.1.js" type="text/javascript"></script>
    
answered by 29.01.2018 в 20:40
0

Test modifying

$("#botonExportar").click(function(){
   .......
   ........

 })    

for

 $("#botonExportar").click(function(e){
    e.preventDefault();
   tu código

  })
    
answered by 29.01.2018 в 21:36