Resource Rails with AJAX

On the rails, some kind of AJAX challenge will need to be made to create and modify resources. Tell me if I have such a resource

Man(age: integer, country_from:string, residence:string) 

Now, how to do this through an AJAX call (for example, send a message to my create function, how the parameters will be transferred, how my controllers will be configured). In detail, my AJAX is very, very, very weak. (right now I have my Man made like rails creating the scaffold Man age: int country_from: string ...)

PS

Im using rails 3

+4
source share
2 answers

Therefore, I believe that there are two sides: javascript and the controller are changing.

In your controller, you need to make sure that it can return a json output (or xml or any other ajax-y output you choose):

 def man # do your work return_data = {} # initialize your return data respond_to do |format| render :json => return_data.to_json, :layout => nil end end 

There are many ways to generate your json output, but basically you have to make sure that it is in a form that is easily consumed in a javascript view.

I am using jQuery and here is the code to make ajax call:

 function foo(some_param) { $.ajax({ type: 'GET', url: "/<controller>/man?FOO=" + some_params, dataType: 'json', success: handle_success, error: handle_errors } function handle_success(data) { # process return JSON. it a javascript object corresponding to the shape # of your JSON. If your json was a hash server side, it will be an 'object', etc } function handle_error(data) { # handle error cases based upon failure in the infrastructure, not # failure cases that you encounter due to input, etc. } 

You can bind the foo function to any button or by clicking as you wish.

I am not sure if this is complete enough. Let me know if you need more details, etc.

+1
source

Rails 3 can help by telling the form that you want it to be "remote" (ajax)

 <%= form_for @man, :remote=>true do |f| %> <div class="field"> <%= f.label :man %> <%= f.text_field :man %> </div> <%= f.submit "Save", :disable_with=>"Saving..."%> <% end %> 

in your controllers

 class MansController < ApplicationController respond_to :js, :html def update @man = Man.find(params[:id]) @man.update_attributes(params[:man]) respond_with @man end end 

Then you can /app/views/mans/update.js.erb

 <% if @man.errors.any? %> alert("This is javascript code that either renders the form in place of the other form"); <% else %> alert("success!") <% end %> 

Note: wherever I say β€œmans” above, it can be β€œmen”

+1
source

Source: https://habr.com/ru/post/1383888/


All Articles