Handling two buttons that submit a form using AJAX I am currently handling forms by binding submit event and then calling the ajax() function:

// Code to handle add post form

$('#add_post').on('submit', function (e) {
    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: "add",
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {},
        error: function (data) {}
   })

// Code to handle update post form

$('#edit_post').on('submit', function (e) {
    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: "edit",
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {},
        error: function (data) {}
   })

})


As you can see I have a lot repeating code. How can I refactor my code?
If it's the exact same call you could abstract the Ajax call into its own function and pass the url. For example:

const doAjax = (url) =&gt; {
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {},
        error: function (data) {}
    });
}

doAjax('add');
doAjax('edit');


This is an ES6 function expression but would also work with ES5 function(){} syntax.

function doAjax(url) {
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {},
        error: function (data) {}
    });
}