There is a form with <button type="submit" class="btn-main"> how to send ajax when it is clicked?

    3 answers 3

     <script type="text/javascript"> $(function(){ $('form.main button.btn-main').on('click', function(e){ e.preventDefault(); $.ajax({ url: '/some-url/', data: $('form.main').serialize(), method: 'POST', dataType: 'json', success: function(data){ console.log(data); } }); }); }); </script> 

    See other parameters on ajax and on serialize .

      Maybe you are wondering how to send it by click, without catching the form submit itself.

       <button onClick='func()' class="btn-main"> var func = function(){ $.ajax({ url: '/some-url/', data: 'data', method: 'POST', dataType: 'json', success: function(data){ console.log(data); } }); 

        button type="submit" will trigger a form submission event for you, so it’s more appropriate to use it.

         $(function(){ $('form').on('submit', function(){ $.ajax({ url: $(this).attr('action'), data: $(this).serialize(), method: 'POST', dataType: 'json', success: function(data){ console.log(data); } }); return false; }); });