Home > Software design >  Calling AJAX in Coffeescript
Calling AJAX in Coffeescript

Time:09-26

I have an ajax call that works well in a view, but I would like to make it in a coffee script, right inside a datatable call. The code looks like:

    $(document).ready(function () {
    $.ajax({
      type: "GET",
      url: "<%= people_path(format: :json) %>",
      dataType: "json",
      success: function({data}) {
        const user_ids = data.map(user => user.id)
        $("#people-ids").html(user_ids.join());
      }
    });
  });

I am new to coffeescript, so I need some help to finish the method around the mapping section. I could go as far as this:

ajax:
  type: 'GET'
  url: $('#people-datatable').data('source')
  dataType: 'json'
  success: ({data}) ->

I obtain 7 objects in {data}, but i do not know how to continue to retrieve their ID as in JS. can someone help please ?

CodePudding user response:

In the map iterator function you need to wrap the parameter name in parenthesis. Coffeescript doesn't support the syntax without parenthesis which is allowed in javascript.

It would be ambiguous as it could be interpreted as user => ... being a function user being executed with the argument => ...

This should work:

$(document).ready ->
  $.ajax
    type: "GET",
    url: "<%= people_path(format: :json) %>",
    dataType: "json",
    success: ({ data }) ->
      user_ids = data.map (user) -> user.id
      $("#people-ids").html user_ids.join() 

While you are learning the syntax it might be useful to build snippets in http://coffeescript.org/#try: so you can see what it transpiles to instantly.

  • Related