1

I am trying to make an ajax call to the controller which inturn calls a method from the model and returns to me an array of values. But I am unable to get any response in ajax. I need to set value of a text field depending upon the response data.

My ajax code is written in .coffee.js:

$.ajax({
        url: '/addresses/billing_address_to_string',
        type: "POST"
        dataType: "JSON"
        success: (data) ->
          $('#billing_address_address_line1').val(data)
      }).done

In my controller:

respond_to :json, only: [:billing_address_to_string]
def billing_address_to_string
    address = Address.last.billing_address_to_string1
    respond_with address
  end

The model method is:

def billing_address_to_string1
    address = []
    address << [name, street, street_qualifier].reject(&:blank?)
    address << [city, state_or_region, postal_code].reject(&:blank?)
    address << [phone_number]
  end

Any help would be much appreciated:)

Radhika
  • 2,453
  • 2
  • 23
  • 28

1 Answers1

1

Does Address.last.billing_address_to_string1 return a String? If so you need to wrap it in a hash to JSON encode it.

Try

 respond_with({:address => address})

Then the JS should be

 $.ajax({
    url: '/addresses/billing_address_to_string',
    type: "POST"
    dataType: "JSON"
    success: (data) ->
      $('#billing_address_address_line1').val(data.address)
  })
Slicedpan
  • 4,995
  • 2
  • 18
  • 33
  • I made the changes but no luck:( – Radhika Nov 13 '13 at 09:30
  • 1
    Are you using chrome? In the network tab, you can look at the response of the ajax request. Make sure that the response gives you what you expect. – Slicedpan Nov 13 '13 at 09:38
  • I had made a very silly mistake, in a hurry I simply forgot to add a route for my method. After I added the route I made the changes you mentioned above.It works perfectly now:) Thanks alot for your help.cheers! – Radhika Nov 13 '13 at 14:40
  • No worries, note that it's not technically necessary to wrap an array in an object for a json response, however [not doing so raises security issues](http://stackoverflow.com/questions/3503102/what-are-top-level-json-arrays-and-why-are-they-a-security-risk) – Slicedpan Nov 13 '13 at 14:45