Dominik Krulak
Dominik Krulak

Reputation: 611

Calling click event doesn't submit form with Ajax

I'm calling the click event with <button type="action" value="click"></button> to submit a form with Ajax. To submit form with button type submit works if I don't call the click event. So you can eliminate this possibility. I just need to call the submit function with click event which I doubt I've proceed it right.

The buggy code example:

// On document ready
$(function() {
  $('#update-button').click(function(){
    $('#update-cart').submit(function(ev) {

      // Prevent the form from actually submitting
      ev.preventDefault();
      // Get the post data
      var data = $(this).serialize();

      // Send it to the server
      $.post('/', data, function(response, textStatus, jqXHR) {
        if (response.success) {
        // YES
        } else {
        // Ooo NO
        }
      });
    });
  });
});

Upvotes: 0

Views: 81

Answers (1)

Akshay Chawla
Akshay Chawla

Reputation: 613

// On document ready
$(function() {
  $('#update-button').click(function(event){
      // Prevent the form from actually submitting
      event.preventDefault();
      // Get the post data
      var data = $("#update-cart").serialize();

     // Send it to the server
     $.post('/', data, function(response, textStatus, jqXHR) {
       if (response.success) {
         // YES
       } else {
         // Ooo NO
      }
    });
  });
});

To avoid same id issues which take a hell lot of time to solve, its better to give proper naming conventions to DOM element.

  • Hidden field -> hdnElementName
  • Button -> btnElementName
  • Textbox -> txtElementName

Using such naming conventions will surely remove such mistakes. :)

Upvotes: 1

Related Questions