Andy Harvey
Andy Harvey

Reputation: 12653

How to dynamically update a Rail field from a json request?

Say that a Rails app has a Car and an Order model. The Car model contains name and color fields. The Order model contains a car_id field, and a color field so that the user can specify an alternative color if required.

When a user creates a new Order, they can select the Car name from a select field. How do I dynamically update a text field with the color on this event.

The Order form contains the fields

<select id="order_car_id></select>
<input id="order_color"></input>

The Car show view responds to json

def show
    respond_to do |format|
      format.json { render :json => @car.to_json, :status => 200 }
    end
end 

and this function responds to the event and grabs the json array.

$(function (){
    $('#order_car_id').live("change", function(e) {
    e.preventDefault();
      $.ajax({
        url: "/cars/" + $(this).val(),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            $('#order_color').val(car[0].color);
        },
        error: function(xhr,exception,status) {
          //error functions...
        }
      });
    });
});

but I'm getting

Uncaught ReferenceError: car is not defined

What is the correct syntax for passing a value from the json array into the #order_color field? I've tried various permutations of $('#order_color').val(car[0].color); but can't seem to figure it out.

Grateful if anyone can point me in the right direction and learn how this works.

Thank you!

Upvotes: 0

Views: 552

Answers (1)

redronin
redronin

Reputation: 723

Looks like your success function, you don't define is what car is.

Your function is passing in 'data', but 'car' is not defined anywhere in that function.

You ned to extract car from the data object.

First, add console.log(data) to your success function so you can see the structure of the data response.

function(data) {
  console.log(data);
  //$('#order_color').val(car[0].color);
}

You'll probably get back something like:

data:{
  car:{
    color:"blue"
    size:"large"
  }
}

Once you know the format of your data object, you can access by:

$('#order_color').val(data.car.color);

Upvotes: 1

Related Questions