Search code examples
jquerycode-duplicationredundancy

What's the best way to avoid code duplication in these two functions that do the same thing?


Given this form (which contains a submit button):

<form id="review_form">
  <input type="submit" id="btn_submit" value="Submit with ajax! (submit button)">
</form>

and this link (to submit the same form):

<a href="#" id="lnk_submit">Submit with ajax! (hyperlink)</a>

In the following jQuery code, when the #btn_submit element is clicked, the form (#review_form) is submitted with ajax:

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

$(document).ready(function() {
  $("#btn_submit").submitWithAjax();
})

What I want to do is remove the submit button and submit the form using the link above (#lnk_submit) something like this:

$("#lnk_submit").click(function(){ 
   $("#review_form").submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
    }); 
   return false;
});

But the problem is that this duplicates all of the code in jQuery.fn.submitWithAjax defined above.

What's the best way to avoid the code duplication here?


Solution

  • How about you have a function like this:

    function submitWithAjax() {
        $("#review_form").submit(function() {
            $.post(this.action, $(this).serialize(), null, "script");
            return false;
        });         
    }
    

    And then link both actions to the function:

    $(document).ready(submitWithAjax);
    $("#lnk_submit").click(submitWithAjax);