Forum: Ruby on Rails Easy RoR <-> Javascript syntax question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2009-02-12 18:13
Hi there,

a simple n00b question:

I have that Javascript snippet on my page (see below; taken from jquery,
actually).

I want to pass it the "@cities" array from the controller. But what's
the correct syntax, here?

See the 3rd line:

========================================

<script>
  $(document).ready(function(){
    var data = @cities;       <---- that's not correct, is it?
    $("#city").autocomplete(data);
  });
</script>

========================================

Thanks a lot for helping me!

Tom
4c438a80fc30661ad619ea177cf9cbd0?d=identicon&s=25 Freddy Andersen (Guest)
on 2009-02-12 22:44
(Received via mailing list)
<%= @cities %>
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2009-02-12 23:00
Holy sh...

Thanks! :-)
Dd2d775dea75b381edb1bbf0600a0907?d=identicon&s=25 Marnen Laibow-Koser (marnen)
on 2009-02-13 17:17
(Received via mailing list)
On Feb 12, 12:13 pm, Tom Ha <rails-mailing-l...@andreas-s.net> wrote:
> Hi there,
>
> a simple n00b question:
>
> I have that Javascript snippet on my page (see below; taken from jquery,
> actually).
>
> I want to pass it the "@cities" array from the controller. But what's
> the correct syntax, here?
[...]
> <script>
>   $(document).ready(function(){
>     var data = @cities;       <---- that's not correct, is it?
>     $("#city").autocomplete(data);
>   });
> </script>

Small note: you really should not be using inline JavaScript (see
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript for more
information).  So while Freddy's solution will work, I would suggest
putting your JavaScript in a separate file.  In this case, there are
two ways to get the value of @cities into the JavaScript code:

1. Use a .js.erb file and embed the value in ERb, just as you would in
an inline script.  This is very simple, but has the disadvantage that
the browser cannot cache the script file, since the code is
dynamically generated every time.
2 (my usual method).
---stylesheet---
.hidden: {display: none;}
---view---
<div id="cities" class="hidden"><%= @cities %></div>
---JavaScript---
$(document).ready(function(){
  var data = $("#cities").innerHTML().doWhateverYouNeedToParseIt()
  $("#city").autocomplete(data);
});

Good luck!

Best,
--
Marnen Laibow-Koser
marnen@marnen.org
http://www.marnen.org
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2009-02-13 17:53
Thanks for your comment !
Tom
This topic is locked and can not be replied to.