1
\$\begingroup\$

I am submitting my form using ajax. Here is the actual code:

// generic ajax caller
function ajaxHandler(url, data, options)
{
    return $.ajax($.extend({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: data,
            success: function (data) {
                return data;
            },
            error: function (xhr, textStatus, error) {
                return error;
            },
        }, options))

};



   // This code handles course submission form 

     $('#add-course').on('submit', function (e) {
    e.preventDefault();

    var form = $(this);

    ajaxHandler(form.url, form.serialize()).then(function (result) {

        console.log('#############');

        $('.field-error, .success, .error').remove();
        if(result.errorType == "fieldErrors")
        {
            // handle field errors
            $.each(result.data, function (key, value) {
                console.log(key, value);
                $('<span class="field-error"> ' + value.msg + '</span>').insertBefore('#' + value.param);
            });
        }

        else if(result.errorType == "formErrors")
        {
            // handle form errors
            $('<p class="error">' + result.message + '</p>').insertBefore(form);
        }

        else
        {
            // success
            form[0].reset();
            $('<p><span class="success">' + result.message + '</span></p>').insertBefore(form);
        }

    })
    .fail(function (error) {
        $('<p ><span class="error">Error connecting server</span></p>').insertBefore(form);
    });

});


// Here is code which handles update course form
$('#change-course').on('submit', function (e) {
    e.preventDefault();

    var form = $(this);

    ajaxHandler(form.url, form.serialize()).then(function (result) {

        $('.field-error, .success, .error').remove();
        if(result.errorType == "fieldError")
        {
            // handle field errors
            $.each(result.data, function (key, value) {
                console.log(key, value);
                $('<span class="field-error"> ' + value.msg + '</span>').insertBefore('#' + value.param);
            });
        }

        else if(result.errorType == "formError")
        {
            // handle form errors
            $('<p><span class="form-error">' + result.message + '</span></p>').insertBefore(form);
        }

        else
        {
            // success
            $('<p><span class="success">' + result.message + '</span></p>').insertBefore(form);
        }

    })
        .fail(function (error) {
            $('<p><span class="error">Error connecting server</span></p>').insertBefore(form);
        });
});

As you can see the structure of add/update form is almost the same. How can I refactor all this?

\$\endgroup\$
  • \$\begingroup\$ Why are you using $.extend() to merge the options parameter of ajaxHandler() with the rest of the data? You don't seem to be passing anything to options either time you call ajaxHandler()... \$\endgroup\$ – Tim Aug 16 '17 at 3:23
  • \$\begingroup\$ There are other actions which uses this , that's why \$\endgroup\$ – Cody Aug 16 '17 at 3:28
1
\$\begingroup\$

I think most of the code duplication can be taken care of by simply creating success and failure functions to handle the ajax response for both your forms. Additionally, if you're only sometimes going to pass a value to options in the ajaxHandler function, you should check if it's undefined.

// generic ajax caller
function ajaxHandler(url, data, options) {
  var ajaxOptions = {
    type: 'POST',
    url: url,
    dataType: 'json',
    data: data,
    success: function(data) {
      return data;
    },
    error: function(xhr, textStatus, error) {
      return error;
    }
  };
  return (options === undefined) ? $.ajax(ajaxOptions) : $.ajax($.extend(ajaxOptions, options));
};

function success(result, form, reset) {
  $('.field-error, .success, .error').remove();
  if (result.errorType == "fieldErrors") {
    // handle field errors
    $.each(result.data, function(key, value) {
      console.log(key, value);
      $('<span class="field-error"> ' + value.msg + '</span>').insertBefore('#' + value.param);
    });
  } else if (result.errorType == "formErrors") {
    // handle form errors
    $('<p class="error">' + result.message + '</p>').insertBefore(form);
  } else {
    // success
    if (reset) {
      form[0].reset();
    }
    $('<p><span class="success">' + result.message + '</span></p>').insertBefore(form);
  }
}

function failure(form) {
  $('<p><span class="error">Error connecting server</span></p>').insertBefore(form);
}

// This code handles course submission form 
$('#add-course').on('submit', function(e) {
  e.preventDefault();
  var form = $(this);
  ajaxHandler(form.url, form.serialize())
    .then(function(result) {
      console.log('#############');
      success(result, form, false);
    })
    .fail(function(error) {
      failure(form);
    });
});

// Here is code which handles update course form
$('#change-course').on('submit', function(e) {
  e.preventDefault();
  var form = $(this);
  ajaxHandler(form.url, form.serialize())
    .then(function(result) {
      success(result, form, true);
    })
    .fail(function(error) {
      failure(form);
    });
});
\$\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.