ruby on rails - What is better - use ajax calls from assets/javascript/*.js or *.js.erb views? -


i'm writing admin service network communicator using rails.

so problem: user clicks button -> groups user sees network groups -> user chooses group -> user sees ip addresses. have 2 forms on page , need send data page 2 times without page reloading.

the first server response list of network group names.

the second server response list of ip addresses in 1 of groups.

question:

which better after user request:

  1. js.erb way

    get data, put views/some_file.js.erb, write "respond_to{ |format| format.js }" in controller. expected result: browser recieve js, js code run on client, js code append data table on page.

  2. js ajax in assets/javascript way

    send data in json format client. js code make ajax call server, bowser recieve json-data form server, js append data table on page.

please, explain advantages , disadvantages of both ways. thanks.

i'd best way make ajax request controller action groups#names in groups_controller.rb , have action render json.

do in javascript asset such app/assets/javascripts/script.js so:

$('#get-group-names-button').live('click', function(event) {   event.preventdefault();   $.ajax({     url: "/groups/names",     type: 'post',     data: {'groupid': 'whatever'}   }); }); 

then in groups_controller

def names   if group_names     render :json => group_names, :status => 200   else     render :status => 400   end end 

then parse json response using jquery done() on client , append data whatever html formatting need in javascript.

this can aided using client-side framework backbone.js, , templating language handlebars.

here railscast on topic produced ryan bates


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -