0

I have a json response in my controller action that looks like this

def index
  ...
  @activities = Activity.includes(:tasks).all

  respond_to do |format|
    format.json {render :json => @activities.to_json(:only=>[:id,:name],:include=>[:tasks])}
  end

end

and I get this response:

[{"id":1,"name":"Act1","tasks":
  [{"id":30,"name":"task1"},{"id":29,"name":"task2"},{"id":27,"name":"task3"}]},   
 {"id":7,"name":"Act2","tasks":
  [{"id":31,"name":"tt1"},{"id":28,"name":"tt2"},{"id":30,"name":"tt3"}]},  
 {"id":8,"name":"Act3","tasks":
  [{"id":31,"name":"N1"},{"id":33,"name":"N2"},{"id":28,"name":"N4"}]}
}]

and I use that using this ajax call

  $("#linkto").click(function(e){
    e.preventDefault();
    $.ajax({
      type    : "GET",
      url   : "/activities.json",
      success: function(data) {
        var act = $.map(data, function(f){
            return "<p>" + f.name + "</p>" + "<ul>" + 
            $.map(f.tasks,function(g){
              return "<li>" + g.name +"</li>";
            }).join(''); + "</ul>";
          });
        $('#ctypes').html(act.join(''));
      }
    });
  })

and I expect to show this:

<p>NAME</p>
<ul>
  <li>task1</li>
  ....
</ul>
<p>NAME</p>
<ul>
  <li>task1</li>
</ul>
.........

but I get this

<p>NAME</p>
<ul>
  <li></li>
  ...
  <p>NAME</p>
  <ul>
    <li></li>
    ....
    <p></p>
    <ul>........
  </ul>

How can I format my ajax success?

Thanks

Javier Q

JavierQQ23
  • 704
  • 1
  • 8
  • 20

1 Answers1

0

You have an extra semi colon on line 11. Correct code is:

$("#linkto").click(function(e){
  e.preventDefault();
  $.ajax({
    type    : "GET",
    url   : "/activities.json",
    success: function(data) {
      var act = $.map(data, function(f){
          return "<p>" + f.name + "</p>" + "<ul>" + 
          $.map(f.tasks,function(g){
            return "<li>" + g.name +"</li>";
          }).join('') + "</ul>";
        });
      $('#ctypes').html(act.join(''));
    }
  });
});

IMHO string concatenation is easier to debug/maintain and is faster as well (see Why is string concatenation faster than array join?)

Below is a little easier on my eyes, but YMMV.

$("#linkto").click(function(e){
  e.preventDefault();
  $.ajax({
    type    : "GET",
    url   : "/activities.json",
    success: function(data) {
      var html = '';
      for (var a=0, aLen=data.length; a<aLen; a++) {
        html += "<p>" + data[a].name + "</p>";
        html += "<ul>";
        for (var t=0, tLen=data[a].tasks.length; t<tLen; t++) html +=  "<li>" + data[a].tasks[t].name +"</li>";
        html += '</ul>';
      }
      $('#ctypes').html(html);
    }
  });
});
Community
  • 1
  • 1
Krut
  • 4,112
  • 3
  • 34
  • 42