Jack
Jack

Reputation: 3878

Rails form lookup details in javascript and post to page

I'm new to javascript / coffeescript / jQuery, but want to implement the following in my Rails application. What should I look into to get this working?

The text field has an id of personNumber and I want it to look up the associated name for the value in the People table and post it into the page to a div with id persondetails.

$ -> $("#personNumber").focusout(show_message)
show_message = -> $("#persondetails").html("Name will go here");  

Upvotes: 0

Views: 237

Answers (1)

mu is too short
mu is too short

Reputation: 434615

You just need to add a bit of AJAX to what you already have:

$ ->
    $('#personNumber').focusout(show_message)
    show_message = ->
        id = encodeURIComponent($('#personNumber').val())
        $.ajax
            url: '/path/to/your/controller/' + id + '/name'
            type: 'get'
            success: (data) ->
                $('#persondetails').html(data.name)
            error: ->
                # Do something sensible

Then you'd route /path/to/your/controller/:id/name to a controller method sort of like this:

def your_method
    #... look up params[:id] and leave the person in `person`
    if(person)
        render :json => { :name => person.name }, :status => :ok
    else
        render :json => { :msg => 'some error message' }, :status => :not_found
    end
end

If you wanted to be able to look up names based on things other than just the ID, you could add some flexibility like this:

$ ->
    $('#personNumber').focusout(show_message)
    show_message = ->
        $.ajax
            url: '/path/to/your/controller'
            type: 'get'
            data: { id: $('#personNumber').val() }
            success: (data) ->
                $('#persondetails').html(data.name)
            error: ->
                # Do something sensible

Then route /path/to/your/controller to a controller method as above and add a bit more logic to your_method to be able to find the person based on other things that might be params.

You might want to add a "loading..." message as well. You could show a "loading..." <div> before calling $.ajax and hide it in the complete callback from $.ajax.

Upvotes: 1

Related Questions