Access ruby array in javascript - javascript

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)');
}

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.

You can do this by using the
to_json
method in Ruby
or
render :json => #contacts

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.

Related

Sending large Model list from view to controller c# mvc razor

I have got very large model list in view and i would like to send the list back to controller using ajax query. I have tried to send the whole model list back but since the model is too large, it exceeds the json maxlength specified within web.config. The encode method works for smaller list though.
var jsonString = #Html.Raw(Json.Encode(Model.modelName_small));
Only way that i can vision it to work is but filtering the large model list into smaller list using javascript (similar to a 'Where' SQL statement). My script are as follows (razor):
<script type="text/javascript" language="javascript">
function functionName(input1_decimal) {
var smallerList = new Array();
#foreach (var item in Model.modelName)
{
//input1_decimal should be within a certain range
#:if (input1_decimal - 0.1 <= #item.Property1) && (#item.Property1 <= input1_decimal + 0.1)
{
#:smallerList.push("#item");
}
}
//convert smallerList to json and send it to controller
}
<script>
it seems quite straight forward but I just can not get it to work. Might be something quite trivial. I have also tried:
var smallerList= Model.modelName.Where(x => (input1_decimal - 0.1 <= x.Property1) && (x.Property1 <= input1_decimal + 0.1));
Similarly, i have also tried
var smallerList = Model.modelName.filter(function (item) {
return (input1_decimal - 0.1 <= item.Property1) && (item.Property1<= input1_decimal + 0.1)
});
Thank you for your patience. i hope i have explained it clearly as to what i am trying to achieve. I am not a developer. Programming just for fun and self education.
Are you modifying data on the view ? If so, one other approach is to post only modified data to the controller in order to minimized the json string length and retrieve the rest of the data directly in the controller.
instead of editing jsonmaxlength field within web.config, I assigned MaxJsonLength to Int32.MaxValue. Created a list and assigned properties to model properties and serialise into Json object list. Then i filtered the list using $.grep function. Finally, I was able to send objJsonSmallList back to controller... Happy days :)
#{
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue;
//Create a list and assigning all the properties of the model
var data = Model.model_Name.Select(x => new
{
propName1 = x.property1,
propName2 = x.property2,
...
propNameN = x.propertyN
});
//serialize collection of anonymous objects
string strArr = js.Serialize(data);
}
var objJsonBigList = JSON.parse('#strArr'.replace(/"/g, '"'));
//small Filtered list send to controller via Ajax
var objJsonSmallList = $.grep(objJsonBigList, function (n) {
return ((input1_decimal- 0.1 <= n.Prop) && (n.Prop <= input1_decimal + 0.1))
});

How to substitute a series of keys into a string being displayed using javascript?

I have a set of templates that contain key phrases denoted by %%key%% (could use different delimiters if these are a problem). In the code presented, the names of the templates are shown in a selector, and when selected, their values are presently being moved into a textarea for display. Before they are displayed, I wish to go through the template and replace each key with the value associated with that key.
I have tried using template.gsub 'key' 'value', template.gsub! 'key' 'value', and even template['key'] = 'value', to no avail. To eliminate other problems, I have tried using simple values for the 'value' and then displaying the result in an alert. If I don't try the replacement, the alert shows the template. If I try any of these attempts, I don't get the alert to show, indicating some kind of javascript error, I suppose. I can't figure out what the error is.
Here is a part of the application_helper.rb:
#----------------------------------------------------------------------------
def render_haml(haml, locals = {})
Haml::Engine.new(haml.strip_heredoc, format: :html5).render(self, locals)
end
#----------------------------------------------------------------------------
def create_template_selector
get_templates()
render_haml <<-HAML
%select{{name: "msg", id: "template_selector"}}
- #t_hash.each do |name,message|
%option{ :value => message }= name
HAML
end
#----------------------------------------------------------------------------
def get_templates()
templates = Template.all
#t_hash = Hash.new
templates.each do |t|
#t_hash[t.name] = t.message
end
end
and this is the view partial _text.html.haml, where the selector is embedded and its selection is presented when changed:
= form_for(#comment, remote: true, html: {id: "#{id_prefix}_new_comment"}) do |f|
= hidden_field_tag "comment[commentable_id]", commentable.id, id: "#{id_prefix}_comment_commentable_id"
= hidden_field_tag "comment[commentable_type]", class_name.classify, id: "#{id_prefix}_comment_commentable_type"
%div
%h3 Select a Template
= create_template_selector
%div
= f.text_area :comment, id: "#{id_prefix}_comment_comment", name:"text_msg"
.buttons
= image_tag("loading.gif", size: :thumb, class: "spinner", style: "display: none;")
= f.submit t(:add_note), id: "#{id_prefix}_comment_submit"
#{t :or}
= link_to(t(:cancel), '#', class: 'cancel')
:javascript
$(document).ready( function() {
$('#template_selector').change(function() {
var data= $('select').find('option:selected').val();
//
// Here is where I put alert(data) and it works
// but,
// var filled = data.gsub '%%first_name%%' 'Ralph'
// followed by alert(filled), shows no alert panel and no error
//
$("##{id_prefix}_comment_comment").val(data);
});
} );
How can I create a set of fill_ins like:
def fill_ins()
#fillins = Hash.new
#fillins['%%first_name%%'] = 'Ralph'
#fillins['%%last_name%%'] = 'Jones'
...
end
and create a function like:
def fill_in(template)
#fi = fill_ins()
#fi.each do 'fkey, fval'
template.gsub! fkey fval
end
end
and have it work?
In :javascript block, you should be writing JavaScript, not Ruby.
String#gsub is a Ruby method.
String.prototype.replace is a JavaScript method.
var filled = data.replace(/%%first_name%%/g, 'Ralph');
EDIT: Forgot that replace with a string only replaces once. Use regular expression with global flag instead.
Also: to pass the data from Ruby to JavaScript, use this pattern in your template:
<script>
const fillIns = <%= fill_ins.to_json %>;
</script>
Then you can either loop that array and run the replace method with each pair (not optimal) — or you can use a regular expression that picks up on the general pattern of the variable:
var filled = data.replace(/%%([^%]+)%%/g, (_, name) => fillIns[name]);

Correct proceedure for JSON/Javascript parsing in Rails?

In Rails, I am querying the database to build a data object for highcharts.
Here is my method from my controller:
def build_data_for_chart
data_array = Array.new
#data_array_as_json = ''
#issues.each {
|issue|
# returns an array of KeyIssue objects for a given issue
given_issue_array = KeyIssues.where(issue: issue).all
a = Array.new
#loop through each element extracting the timedate and % and add to new array
given_issue_array.each {
|entry|
a.push([entry.datetime.utc.to_date, entry.percentage])
}
#build the hash for an individual issue
temp_hash = {:name => issue, :data => a, :animation => false}
#add the individual issue and all its data to a final array that contains all the issues.
data_array.push(temp_hash)
}
#data_array_as_json = data_array.to_json.html_safe
end
Now I am trying to pull it out in a script in my view.
--- script ---
var data = $.parseJSON(<%= #data_array_as_json %>);
--- script ---
When I print to console, I can see the objects and all their data. Also when I print to html the output looks correct:
"[{\"name\":\"ABORIGINAL & NATIVE TITLE ISSUES\",\"data\":[[\"1993-11-01\",32],[\"1994-06-01\",27],[\"1994-09-01\",33],[\"1995-06-01\",26],[\"1995-09-01\",24],[\"1996-01-01\",20],[\"1996-09-01\",27],[\"1997-01-01\",33],[\"1997-06-01\",36],[\"1997-09-01\",36],[\"1998-01-01\",37],[\"1998-05-01\",33],[\"1998-09-01\",31],[\"1999-05-01\",30],[\"1999-09-01\",28],[\"2000-01-01\",30],[\"2000-05-01\",31],[\"2000-09-01\",34],[\"2001-01-01\",32],[\"2001-06-01\",29],[\"2001-09-01\",28],[\"2002-02-01\",25],[\"2002-06-01\",27],[\"2002-10-01\",25],[\"2003-02-01\",24],[\"2003-06-01\",26],[\"2003-10-01\",27],[\"2004-02-01\",27],[\"2004-06-01\",26],[\"2005-06-01\",30],[\"2006-06-01\",27],[\"2007-06-01\",31],[\"2008-07-01\",29]],\"animation\":false}]"
But when I go to print the data variable it is null (obviously due to not being valid input). What am I messing up?
FYI..
I needed to wrap it in single quotes.. to make it work..
$.parseJSON(' <%= #data_array_as_json %> ');
You can try this:
<script type="text/javascript">
var data = <%== data_array.to_json %>
</script>

JavaScript Issue with JSON objects

I've got a function that queries my database and gets a list of usernames-- I've pasted it below:
*dbQuery.jsp*
<%!
org.json.JSONArray dbQuery(String SQL_STRING)
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session1 = sessionFactory.openSession();
org.hibernate.Query query = session1.createQuery(SQL_STRING);
java.util.List list = query.list();
org.json.JSONArray jsonArray = new org.json.JSONArray(list);
// Actual contact insertion will happen at this step
session1.flush();
session1.close();
return jsonArray;
}
%>
I then try to parse through the list of users, but can't get it to work right. Here's what I'm doing:
var users = <%=dbQuery("FROM Users")%>;
alert("User= " + users[0].getAttribute('username'));
Why doesn't this work? What is the right syntax to parse through the objects/attributes in this JSON Array?
users[0].getAttribute('username')
will not work
try
users[0].username

Reading C# dictionary in Javascript

I have a dictionary variable in C# (ASP.NET). I want to send this data to Javascript. I am using this code to serialize it and send to javascript.
Dictionary<string, string> chat;
chat = new Dictionary<string, string>();
chat.Add("Sam", "How are you?");
chat.Add("Rita", "I am good");
var serialize = new System.Web.Script.Serialization.JavaScriptSerializer();
Response.Write(serialize.Serialize(chat));
On the Javascript page, I am calling this page using this;
$.ajax({
url: "TextChatCalls/getChat.aspx",
type: "POST",
context: document.body,
success: function (response) {
var Chats = response.split('\n')[0];
alert(Chats);
}
});
The value in Chats var is {"Sam":"How are you?","Rita":"I am good"}
I don't know how do I read this value in Chats. Can I anyhow convert this into a 2D array and read it as array[0][0], array[1][0] etc. ?
Thanks.
EDIT:
One more confusion is that, the response object, returned from ASP.NET, contains
{"Sam":"How are you?","Rita":"I am good"}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="getChat.aspx?Id=141755" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZJctiKZK4rXVndR3mbGssIarCrOF" />
</div>
<div>
</div>
</form>
</body>
</html>
And not just {"Sam":"How are you?","Rita":"I am good"} as expected. And hence I have to split the response object by var Chats = response.split('\n')[0]; which makes it an string!
You read like this:
alert(Chats["Sam"]);
(so like a C# Dictionary :-). You read/write to it using something like Chats["propertyName"])
or, to go through each value:
for (var c in Chats)
{
if (Chats.hasOwnProperty(c))
{
alert(c + ' ' + Chats[c]);
}
}
Note that this is different than C#. In C# c would contain a KeyValuePair<> containing both the key and the value. In Javascript c is only the key and to get the value you have to use Chats[c].
(the reasoning for hasOwnProperty is here http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)
Now... If you really want to split it:
var array = [];
for (var c in Chats)
{
if (Chats.hasOwnProperty(c))
{
array.push([c, Chats[c]]);
}
}
Just add the data type json to your ajax request
$.ajax({
url: "TextChatCalls/getChat.aspx",
type: "POST",
dataType: "json"
context: document.body,
success: function (response) {
// do something with response
});
This will make response a javascript object that you can access like this
alert(response["sam"]) //How are you?
to split that up into a 2d array just do this
var Chats = [];
for ( k in response ){
Chats[Chats.length] = [k, response[k]];
}
I guess the important point here is that you properly understand what is going on on the JavaScript client side. The datatype that arrives on the JavaScript client side is a JSON string. JSON (= JavaScript Object Notation) can directly be interpreted by JavaScript.
A JavaScript object looks as follows:
var anObject = { name: "Sam", surname: "abc"};
You can access the properties of a JavaScript object either through a somewhat Dictionary-similar way like
anObject["name"] //will get "Sam"
or directly (property notation)
anObject.name
Instead a similar JSON string would look like
var aJsonString = '{ "name": "Sam", "surname": "abc"}'
Now to convert the JSON string to a JavaScript object you need to parse it. jQuery does this already for you, otherwise you can invoke JSON.parse(aJsonString) and you'll get a valid JavaScript object.
Here I did a quick example: http://jsbin.com/adejev/2/edit
For ASP.NET Core, I used this inside the cshtml file. Basically I rebuilt the entire Dictionary into Javascript. The reason for this approach is because I have subfunctions in Javascript that won't be able to call the server model functions with dynamic parameters on events like keypress.
var ModelZxcvWarnLookup = {};
#foreach (var kvp in Model.View.ZxcvbnWarningMsgLocalization)
{
#:ModelZxcvWarnLookup['#Html.Raw(#kvp.Key)'] = '#Html.Raw(#kvp.Value)';
}
Inspecting the html page fetched by the browser:
var ModelZxcvWarnLookup = {};
ModelZxcvWarnLookup["Straight rows of keys are easy to guess"] = "Chinese Straight rows of keys are easy to guess";
ModelZxcvWarnLookup["Short keyboard patterns are easy to guess"] = "Chinese Short keyboard patterns are easy to guess";
ModelZxcvWarnLookup['Repeats like "aaa" are easy to guess'] = 'Repeats like "aaa" are easy to guess';

Categories