Rails3 UJS update not displaying

247 Views Asked by At

I'm having trouble getting a UJS call to update the page display. I want to update the value of a div when a select box changes (I've googled all over the place but to no avail).

I setup the change function like so (I'm using Haml):

%script
  $("#timesheet_worker_id").change(function() {
  -# This works, so we know we're responding to the change event: 
  -# alert('Fired the change function');
  $.ajax({url: "/timesheet_show_worker_name",
  async: false,
  data: 'selected=' + this.value,
  dataType: 'script'})
  });
  });

My controller has the following:

def show_worker_name
  calculated = 'Adam Bilbo'
  render(:update) {|page|
    ### The following works just fine!
    #page << "alert('This is a test')"
    ### This doesn't; DOM is updated but not displayed; test data for now
    page << "$('#timesheet_worker_name').val('Adam Bilbo')"
  }
end

My view has (I'm using simple_form):

=f.association :worker, :collection => Worker.all(:order => 'worker_number'), :prompt => 'Select a worker', :label_method => :worker_number, :label => "Worker Number", :input_html => {:class => 'startField'}
%p{:id => :timesheet_worker_name}

When the ajax call completes, I inspect the DOM and the value is there; i.e., in the console:

$('#timesheet_worker_id").val()

displays 'Adam Bilbo', but the value is not displayed on my page.

I'm running Rails 3.0.9 and gem jquery-rails 1.0.9; any help figuring out what I'm overlooking is most appreciated! Thanks.

RESOLVED - Solution by @iWasRobbed below works. However, basic issue was using val() instead of text() when updating '#timesheet_worker_name' and so my original approach also works with that change.

1

There are 1 best solutions below

3
On BEST ANSWER

Let's restructure this a little bit...

:javascript
  $('#timesheet_worker_id').change(function() {
    $.ajax({
      url: '/timesheet_show_worker_name',
      data: { 'selected': $(this).value },
      success: function (json) { 
        $('#timesheet_worker_name').text(json.name);
      },
      error: function (response) {
        alert('Oops, we had an error.');
      }
    });
  });

And your controller action would be:

def show_worker_name
  calculated = 'Adam Bilbo'
  render :json => { :name => calculated }, :status => :ok
end