Jump to content

The ultimate community for Ruby on Rails developers.


Photo

CRUD model in a bootstrap modal with jquery, ajax - best practice

jquery ajax bootstrap-modal CRUD

  • Please log in to reply
No replies to this topic

#1 cristal-ice

cristal-ice

    Passenger

  • Members
  • 1 posts

Posted 19 September 2013 - 03:43 PM

Hi,

i have an model, which i want to show edit and update in a dialog via ajax. 

What i do at the moment:

 

To open the Modal and render the partial, i send an ajax request to controller#show with ujs

 

this is the link:

<a class="person-dialog" data-remote="true" data-type="script" href="/en/people/32" onclick="return false">Fidel Markus Armstrong</a>

 

this runs the script in new.js.erb which renders the show partial inside the dialog and opens it.

 

To get the edit form, i do the same

<a class="person-dialog" data-remote="true" data-type="script" href="/en/people/32/edit" onclick="return false">Fidel Markus Armstrong</a>

this runs edit.js.erb

 

Now: To update my model, i send the form data as json to the controller#update

<form accept-charset="UTF-8" action="/en/people/32" class="form-horizontal" data-remote="true" data-type="json" id="edit_person_32" method="post">

 

if there is an error in the form, i do render_to_string(form_partial) inside the controller and respond with this inside of the json response.

Now i have the partial html inside of the json object. I do this, to get the rails error messages and fields_with_errors.

 

Is there a better way to do it? all the mix between script and json format and the partial html inside the json doesn't feel right.

 

 

This is the ajax for the form submit:

 

$('#dialog').on('submit', ->
  $(this).find('form').unbind('ajax:beforeSend').bind('ajax:beforeSend',(evt, xhr, settings)  ->
 
  ).unbind('ajax:success').bind('ajax:success',(evt, data, status, xhr) ->
 
    #insert Data to selectbox it there comes a type attribute with the request
    if xhr.status == 201 # :created
      url = data.url #this is en/people/:id
 
#     Load show dialog on success - runs show.js.erb
      $.ajax({
        url: url,
        type: 'get',
        dataType: 'script'
      })
    else
#      Render the dialog html including the error messages and fields with errors
      $('#person-dialog').html(data.error) #data.error is the partial
      $('.field_with_errors input').first().trigger('focus')
      $('.modal-header').prepend(action)
 
    false
 
  ).unbind('ajax:complete').bind('ajax:complete',(evt, xhr, settings) ->
  ).unbind('ajax:error').bind('ajax:error', (evt, xhr, status, error) ->
  )
)

 

 

 

 

 







Also tagged with one or more of these keywords: jquery, ajax, bootstrap-modal, CRUD

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users