1

I am trying to follow the modular js design pattern (revealing) and I have a question. When I bind event listeners like so:

$addClient.submit(ajaxCall);

The event ajaxCall does not run on load. However, when I add parenthesis, like so:

$addClient.submit(ajaxCall());

...it runs on load and does not bind to the event. What gives? I want to add an argument to the ajaxCall() function, but I cannot seem to get it working correctly. Just so you have context, here is the whole code:

var Ajax = (function(){
   var $addClient = $('#add_client');

   $addClient.submit(ajaxCall);


   function ajaxCall(clearFields) {
        console.log('function called');
        var data = $(this).serialize();
        var url = this.action;
        $.ajax({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: data,
            success: function(data) {
                if(data.st === 0) {
                    $messageContainer.html('<p class="alert alert-danger">' + data.msg + '</p>');
                    setTimeout(function(){
                        $messageContainer.html('');
                    }, 7000);
                } else {
                    $messageContainer.html('<p class="alert alert-success">' + data.msg + '</p>');
                    if(clearFields === true) {
                        $('input[type="text"]').val('');
                        $('input[type="email"]').val('');
                        $('textarea').val('');
                    }
                    setTimeout(function(){
                        $messageContainer.html('');
                    }, 7000);
                }
            }
        });
        return false;
    }
})();
dericcain
  • 2,182
  • 7
  • 30
  • 52

2 Answers2

0

You should bind to the body it will get rid of binding issues when the element isn't available, also pass your arguments by wrapping it in an anonymous function:

$('body').on('submit', '#add_client', function () {
    ajaxCall(yourArguments)
});
johnny 5
  • 19,893
  • 50
  • 121
  • 195
  • When using modular design, doesn't it break the rules to add another function to the bound event. The whole point, I thought, was to keep everything separate and modular. With that method, I am just adding another function to call a function. – dericcain Nov 19 '15 at 15:22
0

Is #add_client a form? If so, you need to add it as an event listener on submit. i.e:

$addClient.on('submit', ajaxCall)
// EDIT: If you need arguments, pass ajaxCall.bind(null, arguments) 
Bwaxxlo
  • 1,860
  • 13
  • 18
  • that won't pass any arugments – johnny 5 Nov 19 '15 at 15:14
  • @Bwaxxlo - That fixed it. I read somewhere that the `submit` event was the same as `on('submit', function())` but apparently it is not. It simply adds a listener for the event but does not fire the event. Thanks! EDIT: Actually that didn't fix it. I had the event bound twice. – dericcain Nov 19 '15 at 15:16