Skip to content

Instantly share code, notes, and snippets.

@marksiemers
Last active March 1, 2017 04:28
Show Gist options
  • Save marksiemers/f7392ed42d6a8b63457ba6e2871484cd to your computer and use it in GitHub Desktop.
Save marksiemers/f7392ed42d6a8b63457ba6e2871484cd to your computer and use it in GitHub Desktop.
Sinatra create action with ajax and corresponding JS
# Split a horses create action into separate methods for success and failure.
def post_horses_success
if request.xhr?
content_type :json
as_html = erb :'/horses/_horse_list_item', layout: false, locals: { horse: @horse }
{ horse: @horse, as_html: as_html }.to_json
else
redirect "/horses/#{@horse.id}"
end
end
def post_horses_failure
status 422
@errors = @horse.errors.full_messages
if request.xhr?
erb :'/horses/_horse_form_errors', layout: false
else
erb :"/horses/new"
end
end
post '/horses' do
@horse = Horse.new(params[:horse])
if @horse.save
post_horses_success
else
post_horses_failure
end
end
/*
* START - horses create action
*/
var createHorseFormSuccessHandler = function(response){
$('ul.list').append(response.as_html)
}
var createHorseFormFailHandler = function(response, status, error, $form){
$(response.responseText).insertBefore($form)
}
var createHorseFormAlwaysHandler = function($form){
$form.find('button').prop('disabled', false)
}
var createHorseFormSubmitHandler = function(e){
e.preventDefault()
console.log('createHorseFormSubmitHandler invoked')
var $form = $(this)
var method = $form.attr('method')
var url = $form.attr('action')
var data = $form.serialize()
$('section.errors').remove()
$form.find('button').prop('disabled', true);
var $ajax = $.ajax({
method: method,
url: url,
data: data,
dataType: "JSON"
})
$ajax.done(createHorseFormSuccessHandler)
$ajax.fail(function(response, status, error){
createHorseFormFailHandler(response, status, error, $form)
})
$ajax.always(function(){
createHorseFormAlwaysHandler($form)
})
}
/*
* END - horses create action
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment