Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Ajax, success callback data undefined

So I'm fairly new to Rails.

Heres is my issue:

I have an Ajax call in my coffeescript to a Tenant model, edit page.

$("#tenant_tenantbuildinginfo").change ->
    $.ajax
        url: "/buildings/getgst",
        dataType: "json",
        data: 'buildinginfo' : $(this).val(),
        success: (data) ->
            console.log data
            $("#tenant_gst").val data
        error: (data) ->
            console.log 'error'
    return false

So the idea of this ajax call is to return a tax rate, like "5.6" from the method in the Buildings controller, (which works perfectly)...

   def getgst
     d { 'gets fired' }
     s = Building.get_gst_for_building(params[:buildinginfo])
     d { s.to_s('F') }
     @var = s.to_s('F')

     respond_to do |format|
       format.json { render json: @var }
     end

   end

The d { } lines are the logger, which is why I know the function is being called and returning the correct value. So fine, the Ajax call is working perfectly so far. However, now my issue is parsing or rendering the returning value in the success function.

success: (data) ->
console.log data
$("#tenant_gst").val data

This part of the AJAX call returns "undefined" in my console, which is really weird because in my controller action I'm rendering the @var to json and the ajax call expects json.

Any help appreciated, thanks very much!

like image 535
msadoon Avatar asked Nov 10 '22 06:11

msadoon


1 Answers

undefined means that the data variable is undefined. First of all, the json format expects you to return answer in key: value format, so you should rather go with e.g.:

format.json { render json: { "gst": @var } } in your controller response

You're using wrongly coffeescript, because the success and error methods are passed to data variable, you can try & check how it's parsed to JS here: http://js2coffee.org/

What you probably meant was

$("#tenant_tenantbuildinginfo").change ->
    $.ajax
        url: "/buildings/getgst",
        dataType: "json",
        data: 'buildinginfo' : $(this).val()
        success: (data) ->
            console.log data
            $("#tenant_gst").val data
        error: (data) ->
            console.log 'error'
    return false

(note no comma on the end of line $("#tenant_gst").val data)

Secondly, I would rather try method chain when referring to error / success responses in jQuery call.:

$("#tenant_tenantbuildinginfo").change ->
  $.ajax(
    url: "/buildings/getgst"
    dataType: "json"
    data:
      buildinginfo: $(this).val()
  ).success( (data) ->
      console.log data
      $("#tenant_gst").val data
  ).error( (data) ->
      console.log "error"
  )
like image 191
konole Avatar answered Nov 15 '22 05:11

konole