I want to access a Ruby array in javascript. Please tell me the method to do that. My array is holding the result of a sql query.
@contacts = Contact.order("contacts.position ASC")
I am trying to do this....
for(var i=0; i< a; i++)
{
var firstnameV = "<%=Contact.order('contacts.position ASC')[i].first_name%>";
var lastnameV = "<%=Contact.order('contacts.position ASC')[i].last_name%>";
var emailV = "<%=Contact.order('contacts.position ASC')[i].email%>";
var contactV = parseInt("<%=Contact.order('contacts.position ASC')[i].contact_no%>";
var posV = parseInt("<%=Contact.order('contacts.position ASC')[i].position%>";
tx.executeSql('INSERT INTO contact_table (firstname, lastname, email, contact, pos)
VALUES (firstnameV,lastnameV, emailV, contactV, posV)');
}
-
2Just render json and access it through ajaxapneadiving– apneadiving2011年02月03日 08:44:09 +00:00Commented Feb 3, 2011 at 8:44
-
1@apneadiving Could you please show the steps. I am totally new at rails and ajax.rdp– rdp2011年02月03日 09:07:53 +00:00Commented Feb 3, 2011 at 9:07
3 Answers 3
Quick example of how you can render the value of Ruby variable to JavaScript. Add <%= yield :head %> to head tag in views/layouts/application.html.erb. Then in views/contacts/index.erb (or whatever view you use) add the following:
<%content_for :head do %>
<script type="text/javascript">
window.onload = function() {
alert("First contact in database is <%=Contact.order('contacts.position ASC').first.name%>")
}
</script>
<%end%>
This will alert the first contact name from your database.
9 Comments
var first = is outside <% %> so it will be parsed as a part of html code, not as Ruby code. Use something like <% i = 5 %><%=Contact.order('contacts.position ASC')[i].first_name%> or even a loop, depending what you want.<% @contacts = Contact.order("contacts.position ASC") %><%a = 10%><% for i in 0 do %>var firstname = <%=@contacts[i].first_name%><%end%>You can do this by using the
to_json
method in Ruby
or
render :json => @contacts
1 Comment
Ruby is server side language. JavaScript is mostly (server side also - e.g. node.js) client side. If you want to pass values from Ruby to JS, you could render that value as part of view in script tags or retrieve them via AJAX.