skip to Main Content

I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.

Here’s my Ajax code :

$(document).ready(function () {
    var id_js;

    $(document).on('click', '.btn-success', function () {
        id_js = $('#ID_TXT').val();
        $('form').submit(function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            $.ajax({
                type: "POST",
                url: 'server.php',
                data: {
                    'Mark': 1,
                    'id': id_js,
                },
                success: function (response) {
                    $('#result').html(response);
                }
            });

            return false;
        });
    });
});

Also I have tried .one() and .stopImmediatePropogation() but still no results

2

Answers


  1. The submit handler shouldn’t be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.

    If you want to ensure that the form isn’t submitted until you’ve clicked on the button, add a test in the submit handler.

    $(document).ready(function() {
      var id_js;
    
      $(document).on('click', '.btn-success', function() {
        id_js = $('#ID_TXT').val();
      });
    
      $('form').submit(function(e) {
        if (id_js !== undefined) {
          $.ajax({
            type: "POST",
            url: 'server.php',
            data: {
              'Mark': 1,
              'id': id_js,
            },
            success: function(response) {
              $('#result').html(response);
            }
          });
        } else {
          alert("You need to click on the success button first");
        }
    
        return false;
      });
    });
    Login or Signup to reply.
  2. I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.

    I hope this works well for you.

    
    $(document).ready(function () {
        function postDataToServer() {
            var id_js = $('#ID_TXT').val();
    
            $.ajax({
                type: "POST",
                url: 'server.php',
                data: {
                    'Mark': 1,
                    'id': id_js,
                },
                success: function (response) {
                    $('#result').html(response);
                }
            });       
        }
    
        $(document).on('click', '.btn-success', postDataToServer);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search