SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot fatnic's Avatar
    Join Date
    Aug 2006
    Location
    Lincoln, UK
    Posts
    191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using own Javascript instead of builtin AJAX

    Hi. I'm really starting to get into this Rails thing but have one quick question.

    I prefer to code my own Javascript by hand ad was wondering, if I needed to make any AJAX calls how would I query the server? Would I need to create a separate controller for AJAX queries? Or include methods in the existing controllers?

    Thanks

  2. #2
    Team ********* Louis Simoneau's Avatar
    Join Date
    Sep 2009
    Location
    Melbourne, Australia
    Posts
    228
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hi fatnic,

    Either solution works, though the latter is probably better. The best thing, if you're designing your app RESTfully, is to use the same methods you're already using, but target them to your AJAX call using a respond_to block and a .js format switch. So if you have an index action in your posts controller which returns a list of posts:

    Code Ruby:
    def index
      @posts = Post.find(:all, :limit => 10)
     
      respond_to do |format|
        format.html
        format.xml {render :xml => @posts}
        format.js {render :json => @posts}
      end
    end

    Now if you have a route that includes a format flag like
    Code Ruby:
    map.connect ':controller/:action/:id.:format'
    (map.resource does this by default), all you need to do is request /posts.js instead of /posts to get a JSON serialized version of the posts instead of rendering the full HTML page with layout.

  3. #3
    SitePoint Member
    Join Date
    Nov 2009
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm certainly comfortable enough to hand-code Ajax, or to use Prototype/Jquery. However, Rails has saved me time on the client views by binding the form elements to models (simply naming the form inputs correctly) and by working with JavaScript on or off (remote_form).

    That said, as previously stated - if you've coded your application RESTfully, you should be able to respond to Ajax calls by updating your controller to handle those request types.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •