|
do ($ = jQuery) -> |
|
$.fn.snippet_ajax_form = (options) -> |
|
defaults= |
|
hide_on_success: false |
|
options = $.extend defaults, $.fn.snippet_ajax_form.defaults, options |
|
@each -> |
|
$(@).bind 'submit', -> |
|
# Make a refence to the current form |
|
$self = $ @ |
|
# Set the url |
|
url = $self.prop 'action' |
|
# Set the method/type |
|
type = $self.prop 'method' |
|
# Set all the data from the form |
|
data = $self.serialize() |
|
# Set the redirect url |
|
redirect_url = $self.find('[name="redirect-page-id"]').val() |
|
# Se the confirm message |
|
confirm_message = $self.find('[name="message"]').val() |
|
# Submit the form via ajax |
|
$.ajax |
|
url : url |
|
type : type |
|
dataType: 'html' |
|
data : data |
|
# This will be triggered on success and return an html response |
|
success : (html) -> |
|
# Clean the form and remove any previous errors/messages |
|
$('.ajax-form-field-error, .ajax-form-message').remove() |
|
# Search the html for the errors and extract them |
|
matches= html.match /<strong>[^<]*<\/strong>[^\.]*/g |
|
# If there are matches there must be errors |
|
if matches |
|
# Create the error message for the top of the form |
|
$error_message= $ '<div>', |
|
'class': 'ajax-form-message ajax-form-error hidden' |
|
'text' : 'There were errors in your form, please check below.' |
|
# Add it to the top of the form |
|
$self.parent().prepend($error_message) |
|
# Fade it in |
|
$error_message.fadeIn() |
|
# Display each error next to the correct field label |
|
for match in matches |
|
# Split the match up so one contains the field and the other the |
|
# error message |
|
match = match.split("</strong> ") |
|
# Set the field |
|
field = match[0].replace('<strong>', '') |
|
# Set the error message |
|
error_message = "<span class='ajax-form-field-error'> - #{match[1]}</span>" |
|
# Append the error to the correct field label |
|
$self.find("label:contains('#{field}')").append(error_message) |
|
# If there were no errors the form was submitted successfully |
|
else |
|
# If they have a redirect set then redirect them |
|
if redirect_url isnt "0" then window.location.href= redirect_url |
|
# else display a nice success message at the top with their confirmation message |
|
else |
|
# Create the success message |
|
$success_message= $ '<div>', |
|
'class': 'ajax-form-message ajax-form-success hidden' |
|
'text' : confirm_message |
|
# Add it to the top of the form |
|
$self.parent().prepend($success_message) |
|
# Fade in the success message |
|
$success_message.fadeIn('slower') |
|
# Do we want to hide the form on success? |
|
if options.hide_on_success then $self.slideUp() |
|
# if we don't just clear the form and fade out the success message |
|
else |
|
$self[0].reset() |
|
# Fade out |
|
$success_message.delay(800).fadeOut('slower') |
|
|
|
return false |