problems with ajax request in page with form. jque

2019-09-03 16:53发布

I'm making some things with jQuery ajax function, and I have a problem when I put a form in the middle of the html.
In a nutshell: I have a dummy form that is controlled by the ajax, when it is submitted the ajax function complets the inputs below. The data submited by the ajax is contained in a form tag that is submitted when a button outside the form is clicked. I made that because I need to send the same data in 2 different ways.
The code:
HTML

<input type="button" value="Exportar a Excel" id="xlsexport">
<form action="#" method="post" name="formxls" id="formxls">
    <div class="row">
        <input type="hidden" id="xls" name="xls" value="">
        <div class="item"><span class="negro">Nombre:</span></div>
        <div class="field"><input class="input" id="nombreProv" type="text" /></div>
        <div class="item"><span class="negro">CUIT:</span></div>
        <div class="field"><input class="input" id="cuitProv" type="text" /></div>
        <div class="field"><input type="image" id="btnEnviar" value="Enviar Prov." src="images/botones/mini_send.png" style="margin-top: -1px; margin-left: 8px;" ></div>
    </div>
</form>
... Some inputs below ...


jQuery:

$('document').ready(function(){
   $('#formxls').keypress(function(e){ // it prevents the form will send by pressing enter 
      if(e == 13){
         return false;
      }
    });
   $('#xlsexport').click(function(){
      $('#xls').val('true');
      $('#formxls').submit();
   });
   $('input#btnEnviar').click(function(){
      if($('#xls').val() == 'true') $('#xls').val('');
      $('div#selectData').empty().removeAttr('style');
      $.ajax({ 
          // ajax request code
      });


The problem is:
When I submit the form through the buttom "xlsexport", everything is fine, but then, when I submit the form through the ajax buttom ("btnEnviar"), it does what its supposed to do and then it sends the form, so I lose all the data the ajax loads.
How can I solve it? There are other ways to do this? This is a none sense behavior (at least for me), because I dont have other submit than the one in xlsexport click event.

I hope I made myself clear and you can help me out with this.

Thanks a lot!

2条回答
Summer. ? 凉城
2楼-- · 2019-09-03 17:18

You could define an onSubmit function and check the value of the button clicked, and return false if it is "btnEnviar". Buena suerte.

查看更多
女痞
3楼-- · 2019-09-03 17:21

It probably needs the name attribute in the other input fields (only the hidden input has one).

查看更多
登录 后发表回答