0

Well I have stumbled upon a weird problem.

First time I send the form the server recieves 1. If I send another without reloading the page it sends 2 exact same posts, if I send it again it sends 3 and so on. If I would to send 9 forms it would send 9 exact same posts on the last.

Here's my code:

$('#AskACounsel .btn-ask-question').bind("click", function (e) {
    e.preventDefault();

    var textbox = $('#AskACounselQuestion');
    var question = textbox.val();    
    var product = textbox.data('productid');

    if (question.length > 0) {    
        var params = { question: question, productid: product };    
        var url = '/FAQService/AddQuestion';
        $.ajax({
            url: url, success: function (result) {    
                var infoDiv = $('#AskACounselThankYouView .counsel-info').html(result.Message);
                var backDiv = $('#AskACounselThankYouView .counsel-footer .btn-return');
                if (result.Success) {
                    textbox.val("");
                    backDiv.hide();
                } else {
                    backDiv.show();
                }

                $('#AskACounselDefaultView').hide();
                $('#AskACounselThankYouView').show();
            },
            type: 'POST',
            data: params    
        });
    }    
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Joelgullander
  • 1,624
  • 2
  • 20
  • 46
  • 2
    It sounds like you're somehow attaching this click handler multiple times. – Rory McCrossan Feb 05 '16 at 10:18
  • 1
    Wild speculation: `$('#AskACounselThankYouView .counsel-info').html(result.Message);` adds an element which matches `#AskACounsel .btn-ask-question` nested inside another such element. Clicking on one clicks on all of them, and triggers the click function for each one. – Quentin Feb 05 '16 at 10:20

1 Answers1

1

Its likely that the code you have is passed through many times, i.e. you have a function that has the code and calling it to handle the click event. The rule of thumb is that binding should happen ONLY ONCE, since it's a binding, not just an event handler like "on".

See answer from https://stackoverflow.com/a/8065685/696034 If you want to continue using bind, then unbind before that code through $('#AskACounsel .btn-ask-question').unbind("click"); otherwise, bind the event in the initialization section of your code ONCE.

Community
  • 1
  • 1
Daniel Protopopov
  • 6,778
  • 3
  • 23
  • 39
  • That was the problem. Just like you described the binding stacked up, so if I were to send 9 posts it would bind 9 of them to send 9 – Joelgullander Feb 05 '16 at 10:27