2

Hello people

I'm trying to figured this out, but I still can't do it.

I have a rails 3 app, I'm working with invoices and payments. In the form for payments I have a collection_select where I display all the invoices number (extracted from a postgres database), and what I'm trying to do is when i select an invoice autopopulate others text_fields (provider, address, etc.) without reloading the page, in the same form.

I know I should use ajax, js, jquery, but I'm a beginner in these languages, so i don't know how or where to start

hope you can help me... thanks

Angelo
  • 905
  • 1
  • 17
  • 35

1 Answers1

3

What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.

In your routes:

get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"

In your invoice_controller:

def get_json
  invoice = Invoice.find(params[:invoice_id])
  render :text => invoice.to_json
end

In your invoice model (if the default to_json method is not sufficent):

def to_json
  json = "{"
  json += "id:'#{self.id}'"
  json += ",date_created:'#{self.date}'"
  ...      //add other data  you want to have here later
  json += "}"
end

In your javascript file,

$("#invoice_selecter").change(function(){  //calls this function when the selected value changes
  $.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){  //does ajax call to the invoice route we set up above
    data = eval(data);  //turn the response text into a javascript object
    $("#field_1").val(data.date_created);  //sets the value of the fields to the data returned
    ...
  });
});

You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.

BananaNeil
  • 10,322
  • 7
  • 46
  • 66