updating javascript_include_tag dynamically on show.html.erb - ruby-on-rails

So here is the scenario:
I have 4 entries in a database, they are 4 map routes.
Each map route has its own XML file containing the co-ordinates of each route, I have written an ajax function to pull the data from the xml and write it to a google map
this is an extract from the code
$.ajax({
type: 'GET',
url: '/route4.gpx',
dataType: 'xml',
success: function(track) {
var grids = [];
var bounds = new google.maps.LatLngBounds ();
$(track).find('trkpt').each(function() {
var lat = $(this).attr('lat');
var lon = $(this).attr('lon');
var point = new google.maps.LatLng(lat, lon);
grids.push(point);
bounds.extend(point);
I have this code saved into 4 javascript files where the URL line is different on each (route1.gpx, route2.gpx etc)
What I want to do is on the show.html.erb file is to change the javascript_include_tag to update to the relevant javascript file
So the show.html.erb tags look like the following
<%= javascript_include_tag "http://maps.google.com/maps/api/js?sensor=false" ,"http://code.jquery.com/jquery-1.9.1.min.js", "/js/script1.js" =%>
what I would like is the last reference to change when I visit a different page so
when linked to show/1 the javascript file would be "/js/script1.js"
when linked to show/2 the javascript file would be "/js/script2.js"
when linked to show/3 the javascript file would be "/js/script3.js"
when linked to show/4 the javascript file would be "/js/script4.js"
So is there anyway to write into the javascript_include_tag to achieve this?
All help/suggestions/comments appreciated

You could interpolate the string passed to javascript_include_tag, pass it as an instance variable etc, but I think you are heading down the wrong track. I would have a single javascript function that takes the url to make the ajax request to as a parameter.
You would then call that function with that parameter. You've got several choices here.
You could have a script tag where you generate the function call dynamically, ie you do something along the lines of
$(function(){
my_function(<%= #url.to_json %>)
})
You could have a script tag where you set a window property with the url and use that later:
window.map_url = <%= #url.to_json %>
and then somewhere else
$(function(){
my_function(window.map_url)
})
You could have the function call be part of the static javascript, but have it pull its parameters either from the data attribute of some relevant DOM element
$(function(){
my_function($('some_element').data('url'))
})
I'd usually go for the latter

Why don't you interpolate?
<%= javascript_include_tag "http://maps.google.com/maps/api/js?sensor=false" ,"http://code.jquery.com/jquery-1.9.1.min.js", "/js/script#{controller_variable_for_example_id}.js" =%>

Related

Render partial from jQuery ruby on rails

I wanted to render a partial that contains a form inside of view from application js, I am reading the event of attached button without submitting because I need to process the headers of a file CSV before doing submit.
This is the function:
$(document).ready(function () {
$("#attached_attached_csv").change(function (e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function (e) {
// this line isn't working - I try of many ways, but none are working
$("#text").html("<%= j render partial: 'layouts/form') %>".html_safe);
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
});
I see also how any people using ajax, but I don't know how to use this for the trigger event of an attached button without submitting, I prob sending without html_safe but I obtain the string:
<%= j render partial: 'layouts/form') %>
My partial is "layouts/form", which is a file with extension html.erb. here share where I found the code for handle the event http://jsfiddle.net/FSc8y/2/, but it's not important the most important for me its render the embedded ruby form. Thanks in advance.
You can use rails syntax in your javascript files by adding .js.erb extension to the file name like my_file.js.erb.

rand has the same value when wrapped inside erb tag

I have a new rails app, with a controller Page. The root path is set to 'page#index'.
The app/views/page/index.html has this code:
<h1>Page#index</h1>
<p>Find me in app/views/page/index.html.erb</p>
<script>
setInterval(() => {
console.log(<%= rand %>)
}, 1000)
</script>
Which is truely a bad practice, but I am just curious to know why the console.log(<%= rand %>) line prints the same number every time?
The template is rendered once. If you look at the source of the page you will see one fixed number in the JS code. Reload the page and it is a different number.
If you want a different number every time the JS function is executed you need to do it in JS:
setInterval(() => {
console.log(Math.random())
}, 1000)

html node parsing with ASP classic

I stucked a day's trying to find a answer: is there a possibility with classic ASP, using MSXML2.ServerXMLHTTP.6.0 - to parse html code and extract a content of a HTML node by gived ID? For example:
remote html file:
<html>
.....
<div id="description">
some important notes here
</div>
.....
</html>
asp code
<%
...
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
objHTTP.Open "GET", url_of_remote_html, False
objHTTP.Send
...
%>
Now - i read a lot of docs, that there is a possibility to access HTML as source (objHTTP.responseText) and as structure (objHTTP.responseXML). But how in a world i can use that XML response to access content of that div? I read and try so many examples, but can not find anything clear that I can solve that.
First up, perform the GET request as in your original code snippet:
Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.Open "GET", url_of_remote_html, False
http.Send
Next, create a regular expression object and set the pattern to match the inner html of an element with the desired id:
Set regEx = New RegExp
regEx.Pattern = "<div id=""description"">(.*?)</div>"
regEx.Global = True
Lastly, pull out the content from the first submatch within the first match:
On Error Resume Next
contents = regEx.Execute(http.responseText)(0).Submatches(0)
On Error Goto 0
If anything goes wrong and for example the matching element isn't found in the document, contents will be Null. If all went to plan contents should hold the data you're looking for.

Rendering dynamic scss-files with ajax, rails

As the title suggests, my main objective is to render a dynamic scss(.erb) file after an ajax call.
assets/javascripts/header.js
// onChange of a checkbox, a database boolean field should be toggled via AJAX
$( document ).ready(function() {
$('input[class=collection_cb]').change(function() {
// get the id of the item
var collection_id = $(this).parent().attr("data-collection-id");
// show a loading animation
$("#coll-loading").removeClass("vhidden");
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// removal of loading animation, a bit delayed, as it would be too fast otherwise
setTimeout(function() {
$("#coll_loading").addClass("vhidden");
}, 300);
},
});
});
});
controller/collections_controller.rb
def toggle
# safety measure to check if the user changes his collection
if current_user.id == Collection.find(params[:id]).user_id
collection = Collection.find(params[:id])
# toggle the collection
collection.toggle! :auto_add_item
else
# redirect the user to error page, alert page
end
render :nothing => true
end
All worked very smooth when I solely toggled the database object.
Now I wanted to add some extra spices and change the CSS of my 50+ li's accordingly to the currently selected collections of the user.
My desired CSS looks like this, it checks li elements if they belong to the collections and give them a border color if so.
ul#list > li[data-collections~='8'][data-collections~='2']
{
border-color: #ff2900;
}
I added this to my controller to generate the []-conditions:
def toggle
# .
# .
# toggle function
# return the currently selected collection ids in the [data-collections]-format
#active_collections = ""
c_ids = current_user.collections.where(:auto_add_item => true).pluck('collections.id')
if c_ids.size != 0
c_ids.each { |id| #active_collections += "[data-collections~='#{id}']" }
end
# this is what gets retrieved
# #active_collections => [data-collections~='8'][data-collections~='2']
end
now I need a way to put those brackets in a scss file that gets generated dynamically.
I tried adding:
respond_to do |format|
format.css
end
to my controller, having the file views/collections/toggle.css.erb
ul#list<%= raw active_collections %> > li<%= raw active_collections %> {
border-color: #ff2900;
}
It didn't work, another way was rendering the css file from my controller, and then passing it to a view as described by Manuel Meurer
Did I mess up with the file names? Like using css instead of scss? Do you have any ideas how I should proceed?
Thanks for your help!
Why dynamic CSS? - reasoning
I know that this should normally happen by adding classes via JavaScript. My reasoning to why I need a dynamic css is that when the user decides to change the selected collections, he does this very concentrated. Something like 4 calls in 3 seconds, then a 5 minutes pause, then 5 calls in 4 seconds. The JavaScript would simply take too long to loop through the 50+ li's after every call.
UPDATE
As it turns out, JavaScript was very fast at handling my "long" list... Thanks y'all for pointing out the errors in my thinking!
In my opinion, the problem you've got isn't to do with CSS; it's to do with how your system works
CSS is loaded static (from the http request), which means when the page is rendered, it will not update if you change the CSS files on the server
JS is client side and is designed to interact with rendered HTML elements (through the DOM). This means that JS by its nature is dynamic, and is why we can use it with technologies like Ajax to change parts of the page
Here's where I think your problem comes in...
Your JS call is not reloading the page, which means the CSS stays static. There is currently no way to reload the CSS and have them render without refreshing (sending an HTTP request). This means that any updating you do with JS will have to include per-loaded CSS
As per the comments to your OP, you should really look at updating the classes of your list elements. If you use something like this it should work instantaneously:
$('li').addClass('new');
Hope this helps?
If I understood your feature correctly, actually all you need can be realized by JavaScript simply, no need for any hack.
Let me organize your feature at first
Given an user visiting the page
When he checks a checkbox
He will see a loading sign which implies this is an interaction with server
When the loading sign stopped
He will see the row(or 'li") he checked has a border which implies his action has been accepted by server
Then comes the solution. For readability I will simplify your loading sign code into named functions instead of real code.
$(document).ready(function() {
$('input[class=collection_cb]').change(function() {
// Use a variable to store parent of current scope for using later
var $parent = $(this).parent();
// get the id of the item
var collection_id = $parent.attr("data-collection-id");
show_loading_sign();
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// This is the effect you need.
$parent.addClass('green_color_border');
},
error: function() {
$parent.addClass('red_color_border');
},
complete: function() {
close_loading_sign(); /*Close the sign no matter success or error*/
}
});
});
});
Let me know if my understanding of feature is correct and if this could solve the problem.
What if, when the user toggles a collection selection, you use jquery change one class on the ul and then define static styles based on that?
For example, your original markup might be:
ul#list.no_selection
li.collection8.collection2
li.collection1
And your css would have, statically:
ul.collection1 li.collection1,
ul.collection2 li.collection2,
...
ul.collection8 li.collection8 {
border-color: #ff2900;
}
So by default, there wouldn't be a border. But if the user selects collection 8, your jquery would do:
$('ul#list').addClass('collection8')
and voila, border around the li that's in collection8-- without looping over all the lis in javascript and without loading a stylesheet dynamically.
What do you think, would this work in your case?

How to I preload existing files and display them in the blueimp upload table?

I am using the jquery-ui version of Blueimp upload and I like how I can format a table and display files that were just uploaded. But I'd like to use it as a file manager as well so I want to preload existing files and display than as if they were just uploaded. How can I do that? A sample link to where someone else has addressed this would suffice. BTW, I am uploading several different file types, not just images.
Thanks!
Or without an ajax call:
Prepare array containing details of existing files, e.g:
var files = [
{
"name":"fileName.jpg",
"size":775702,
"type":"image/jpeg",
"url":"http://mydomain.com/files/fileName.jpg",
"deleteUrl":"http://mydomain.com/files/fileName.jpg",
"deleteType":"DELETE"
},
{
"name":"file2.jpg",
"size":68222,
"type":"image/jpeg",
"url":"http://mydomain.com/files/file2.jpg",
"deleteUrl":"http://mydomain.com/files/file2.jpg",
"deleteType":"DELETE"
}
];
Call done callback
var $form = $('#fileupload');
// Init fileuploader if not initialized
// $form.fileupload();
$form.fileupload('option', 'done').call($form, $.Event('done'), {result: {files: files}});
I also had the same problem. It is not magic how it works. I recommend to examine the UploadHandler.php file. Then you will be able to modify this plugin accordind to your needs.
The code above in your second post is just an ajax call to the uploader script (by default index.php in server/php/ folder). The call method is set to "get" by default in $.ajax object.
Open the UploadHandler.php file and go to the class method "initialize(...)". You will see how the call with "get" handled. UploadHandler calls the class method this->get(.:.) to prepare and send the list of existing files. If you use other upload directory, you need pass a parameter to the UploadHänder. Simply chage the url property in the $.ajax object like :
url: $('#fileupload').fileupload('option', 'url')+'?otherDir='+myDir,
then you should initialize the option property of the UploadHandler before you create a new UploadHandler object like this:
$otherDir = trim($_REQUEST['otherDir']);
$otherDir_url = [anyURL] .'/'.$otherDir;//so that the files can be downloaded by clicking on the link
$options = array(
'upload_dir'=> $otherDir,
'upload_url'=> $otherDir_url,
);
$upload_handler = new UploadHandler($options);
Found the code in the main js file... It wasn't obvious how it worked. Got it working just fine.
// Load existing files:
$.ajax({
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).done(function (result) {
$(this).fileupload('option', 'done').call(this, null, {result: result});
});
If any of you looking at this is doing it in .NET, find this: (for me it is in application.js
For a fairly recent version, there is a function
// Load existing files:
$.getJSON($('#fileupload form').prop('action'), function(files) {
files = somethingelse;
var fu = $('#fileupload').data('fileupload');
fu._adjustMaxNumberOfFiles(-files.length);
fu._renderDownload(files)
.appendTo($('#fileupload .files'))
.fadeIn(function() {
// Fix for IE7 and lower:
$(this).show();
});
});
Inside the application.js
I'm doing it for .NET though, and actually needed this gone.
Then set your somethingelse to either your files or "" depending on what you want to show. If you remove the line files = somethingelse then it will preload all files from the folder.

Resources