Search code examples
jqueryajaxjquery-post

jquery ajax form submit is not working


this is my html form

<form id="contactForm1" method="POST" action="downloadfile">
   <input id="tesst" name="tesst" type="hidden" value="<?php echo $val['file_name'];?>"/>
   <div id="download" class="btn btn-danger">Download</div>
</form>

And here is the Jquery function

var frm = $('#contactForm1');
              frm.submit(function(ev) {
                 $.ajax({
                   type: frm.attr('method'),
                   url: frm.attr('action'),
                   data: frm.serialize(),
                   success: function(data) {
                      alert('ok');
                   }
                  });
                 ev.preventDefault();
              });

I don't know much about Jquery.

Please anybody can help me with this?

Thanks.


Solution

  • There are 2 ways to solve your problem

    1. You change your div (download button) to a input submit button and leave your script as it is
    2. You change the function to run when the div is clicked and not when the submit event is fired (the reason is that submit is only fired by a submit button)

    Example: http://jsfiddle.net/Spokey/bNa7d/

    var frm = $('#contactForm1');
    $('#download').click(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok' + data);
            }
        });
    });