0

I'm passing created_at back to my view with the data.when variable.

I now want to use the time_ago_in_words function on this data.

My failed attempt:

<script>
 $('.new_short_message').bind('ajax:success', function(xhr, data, status) {
 $( this ).before( '<p>' + "<%= time_ago_in_words(data.when) %>" + '</p>' );
 });
</script>

This works without the rails function (but I want to get time ago in words)

<script>
$('.new_short_message').bind('ajax:success', function(xhr, data, status) {
 $( this ).before( '<p>' + data.when + '</p>' );
});
</script>
Jai
  • 74,255
  • 12
  • 74
  • 103
grabury
  • 4,797
  • 14
  • 67
  • 125
  • 1
    try to format when with in the response send by the server `{when: time_ago_in_words(created_at)}` – Nitin Jain Jan 30 '14 at 09:37
  • check answers for this question: [http://stackoverflow.com/questions/13840429/reference-why-does-the-php-or-other-server-side-code-in-my-javascript-not-wor] it was for PHP but works for every server side language – waldek_h Jan 30 '14 at 09:42

2 Answers2

1

In Rails:

Using ajax send data.when to receptive controller and get that desire 'words' in this view.

In JavaScript

Use this function to get time_ago_in_word in javascript. I got this code here. So thanks to boxnos.

var time_ago_in_words = function(from, to) {
 to = to ? to : Date.now();

var minutes = (to - from) / 60000;

var data = [
 [0 , 'less than a minute ago'],
 [1 , 'a minute ago'],
 [2 , function(m) {return m.toFixed() + ' minutes ago';}],
 [45 , 'about 1 hour ago'],
 [90 , function(m) {return 'about ' + (m / 60).toFixed() + ' hours ago';}],
 [1440 , '1 day ago'],
 [2880 , function(m) {return (m / 1440).toFixed() + ' days ago';}],
 [43200 , 'about 1 month ago'],
 [86400 , function(m) {return (m / 43200).toFixed() + ' months ago';}],
 [52960 , 'about 1 year ago'],
 [1051200, function(m) {return (m / 525960).toFixed() + ' years ago';}],
 [Number.MAX_VALUE]
];

function b_search(value, lower, pos, upper) {
 if (data[pos][0] <= value && value < data[pos + 1][0])
  return data[pos];
 else if (value < data[pos][0])
  return b_search(value, lower, Math.floor((lower + pos - 1) / 2), pos - 1);
 else
  return b_search(value, pos + 1, Math.floor((pos + 1 + upper) / 2), upper);
}

var res = b_search(minutes, 0, Math.floor((data.length - 1) / 2), data.length - 1)[1];
 return (res instanceof Function) ? res(minutes) : res;
};
rony36
  • 3,277
  • 1
  • 30
  • 42
0

You should always use the escape_javascript method to escape strings. Like This:

<script>
 $('.new_short_message').bind('ajax:success', function(xhr, data, status) {
 $( this ).before( '<p>' + "<%= escape_javascript(time_ago_in_words(data.when)) %>" + '</p>' );
 });
</script>

Otherwise this can cause format failures that cause javascript syntax errors.

davidb
  • 8,884
  • 4
  • 36
  • 72
  • I have tried this but get the error undefined local variable or method `data' for #<#:0x007f97d6865310> – grabury Jan 30 '14 at 10:50