Iacutone.rb

coding and things

JQuery beforeSend Function

| Comments

I have a form which submits a comment via AJAX. The app was throwing validation errors if there was no value in the comment field. My initial solution was to disable the submit button if the comment is blank. However, using the beforeSend function provides a cleaner solution.

1
2
3
4
5
6
7
8
9
10
11
12
  comment = ('.form-field-comment').val()

  $.ajax
    type: 'POST'
    dataType: 'script'
    url: comment_form.attr('action')
    data:
      comment:
        body: comment
    beforeSend: () ->
      if comment is ''
        return false; # do this instead of disabling the submit button 

With the above code, the comment form is never posted if the comment is blank.

Comments