0

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
        }
      });
    });
  });
});
7
  • 1
    What exactly are you trying to do? As you have it now, when you click on #update-button, what it does it bind an submit event to #update-cart. Also I don't think type="action" is valid HTML. You probably want type="submit" or type="button". Commented Apr 19, 2017 at 18:11
  • Have you assigned 'id' to your button i.e update-button ??? Commented Apr 19, 2017 at 18:12
  • @AkshayChawla Yes I did. I think it has to do something with javascript. Commented Apr 20, 2017 at 6:37
  • 1
    jsfiddle.net/zj39mLq2/1 how about this? Commented Apr 20, 2017 at 7:09
  • 1
    @AkshayChawla Yes.That is exactly what I did but still I couldn't see the expected result. So I've logged the process to console and I found out that the click event wasn't fired. I had one hidden input field with id="update-button". So You can post the answer. I'm glad you've helped! ;) Commented Apr 20, 2017 at 7:22

1 Answer 1

1
// 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. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.