1
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

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) => {
    $.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) {}
    });
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.