Javascript in HAML in Javascript - javascript

I've got a question that mightve been asked before but i have trouble finding a proper description. I hope someone can help me out.
In the code below on the line where i set var price i want to add the javascript variable accu_id to find a record in my DB through rails. How do I do this in embedded rails in javascript?
:javascript
$('#accu').change(function() {
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = "#{currency(Product.find_by(id: accu_id).price2)}"
$('#price_accu').append(price)
});
Or is there an easier way to do this?

You have two options.
You can use AJAX request to get data from database
You can use mapping concept like following
var data = #processed_data // json data, which contains processed data in json format.
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = data.accu_id;
Here the #processed_data contains data like following
#processed_data = currency_calculation
def currency_calculation
Product.all.map { |product| [product.id, currency(product.price2) ] }.as_json
end
Example
Assume products table have two entries then the #processed_data contain values like following
{ "1" => "20.00", "2" => "25.50" }
The above data directly assigned to js variable data and accessed like data.key
The first option is best choice and second is possible one.
Note : You can't use js variable inside ruby.

Related

Javascript In Zapier: Split by "-" to multiple outputs

I'm trying to take text in a string like this:
"- Data 1 - Data 2 - Data 3"
And split each of those using javascript into their own "output" for zapier. The goal is to be able to take that data and each data line is used to pre fill a form for a customer like this:
theinternet.com/exampleform/?input1=Data%201&input2=Data%202&input3=Data%203
I either need to be able to use javascript to create the url or have multiple outputs that I can use to integrate with another zap.
There could be as many as 20 data lines or as few as 1 so it needs to be scaleable?
Maybe there is a better way to do it other than javascript?
Does anybody have any ideas?
Problem solved this with a buddy from work. I'm not sure I understand enough to explain it. But this did what we needed to.
var string = inputData.data
var obj = {}
string
.split("- ")
.forEach(function(item, i) {
obj[i] = item
})
output = [obj]

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

KnockoutJS, mapping plugin, get notified when changes in model?

Im using knockoutJS in following way:
var messagesFromServer = getJSONData().messages; //this get msgs from server
ko.mapping.fromJS(messagesFromServer, {}, myobject.viewModel.Messages);
Then i am basically calling this every three seconds to update html table, and it works just fine, new rows are added if new data found from server. Now i would like to add custom callback when something has actually changed, for example when new messages are found.
How should i implement this?
thanks in adv,
-hk
You could convert the two objects into json, then compare them json strings.
var messagesFromServer = getJSONData().messages; //this get msgs from server
var newString = ko.toJSON(messagesFromServer);
var oldString = ko.toJSON(myobject.viewModel.Messages);
if(newString != oldString ) {
// something new
}
ko.mapping.fromJS(messagesFromServer, {}, myobject.viewModel.Messages);
See ko.toJSON doc
I hope it helps.
If the messages is array, you can use ko.utils.compareArrays to detect the changes and raise custom events yourself. Here is code example for comparing ko.observableArray(). Look for Comparing two arrays

Trouble extracting data from 2D array jQuery

I have used Ajax to run a PHP script to return records in a database. I have managed to retrieve the 2D array into my JavaScript file on the success of the Ajax call. I then call a function.
In the function I would like to pull the data from the arrays and save them into JavaScript variables.
I am using jQuery, so I assume I have to use $.each?
Here is the response I am receiving back from the ajax call:
[{"level":"1","location":"4554","quantity":"2","game_item_id":"1"},{"level":"1","location":"4554","quantity":"1","game_item_id":"5"}]
What I am trying to do is extract the level, location data from this 2D array and save it into level and location variables in JavaScript.
Also as you can see the two records being sent back are identical except the game_item_id and the quantity. I want to save a list of the game_item_ids and their associated quantity values into an array or variable.
EDIT
Thanks to answers i have managed to save the level and location data into variables. But im still stumped on how to store each game item id and the quantity of each?
say your object is named data...use loop
$.each(data,function(i,v){
console.log(v.level);
console.log(v.location);
})
Hi refer below code to get id and quantity in array ::
var list =
[{"level":"1","location":"4554","quantity":"2","game_item_id":"1"},{"level":"1","location":"4554","quantity":"1","game_item_id":"5"}];
var arrGameIdAndQuantity = new Object();
for(i=0;i<list.length;i++){
id = list[i]["game_item_id"];
qty = list[i]["quantity"];
arrGameIdAndQuantity[id] = qty;
}
alert(JSON.stringify(arrGameIdAndQuantity))
what about this ;
data[1].level
You can loop through each array like this
data = $.parseJSON(data); // if data is not in json
$.each(data, function(item, value) {
alert(value.level);
alert(value.location);
alert(value.game_item_id);
alert(value.quantity);
});

TaffyDB: Select problems

I'm new to TaffyDB and haven't done a lot of javascript programming so I'm hoping that the problem I'm having is something simple. I'm trying to update a listbox with the options stored in the TaffyDB according to the selected client. When I do my select however, it is returning all the rows.
Below is the code I am using to update the listbox, along with the selectString used to do the query, and what's in the TaffyDB.
Anyone have any ideas why I am getting back all rows when I specify clientID = 1788?
I tried the select string with and without quotes around the column identifier.
// load existing user client projects if we have any
var lbProjects = document.getElementById('lbProjects');
lbProjects.options.length = 0;
var selectString = '{clientID:"' + clientID + '"}';
alert(selectString);
userProjects(selectString).each(
function (r) {
var option = new Option();
option.value = r.projectID;
option.text = r.projectName;
lbProjects.add(option, null);
});
What's in selectString:
{clientID:"1788"}
What's in the DB:
[{"clientID":"1788","projectID":"19"},
{"clientID":"1789","projectID":"24"},
{"clientID":"1790","projectID":"23"}]
Thanks for any help.
Aaron L. Bratcher
The problem was trying to use the selectString variable.
The line
userProjects(selectString).each(
now reads
userProjects({clientID: clientIDValue}).each(
I was supposed to be passing in an object array, not a string. {} in javascript creates an array of objects.

Categories

Resources