Rails: Accessing instance variable from not inline JS - javascript

I have this code in a .html.erb file:
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
FB.Event.subscribe('edge.create',
function(response) {
send_fb_like();
}
);
FB.Event.subscribe('edge.remove',
function(response) {
send_fb_unlike();
}
);
function send_fb_like()
{
var business_name = '<%= #consumer.name %>';
alert("You liked"+consumer_name);
}
function send_fb_unlike()
{
var business_name = '<%= #consumer.name %>';
alert("You unliked"+consumer_name);
}
</script>
This is working correctly, and I can access the #consumer.name correctly. However, if I change this to:
Where facebook_consumer.js looks like this:
$(function(){
FB.Event.subscribe('edge.create',
function(response) {
send_fb_like();
}
);
FB.Event.subscribe('edge.remove',
function(response) {
send_fb_unlike();
}
);
function send_fb_like()
{
var business_name = '<%= #consumer.name %>';
alert("You liked"+consumer_name);
}
function send_fb_unlike()
{
var business_name = '<%= #consumer.name %>';
alert("You unliked"+consumer_name);
}
});
It will dump this:
You liked <%= #consumer.name %>. I have tried saving the file as js.erb, but then it seems it doesn't know what #consumer is.
Any thoughts on what is the best approach?

Your best bet is probably to create an app-wide JS object to store values you need. At the top of the page, you can add elements to this object, and they will be available to your linked scripts.
<script type="text/javascript">
app = app || {}
app.keyName1 = "<%= #variable1 %>";
app.keyName2 = "<%= #variable2 %>";
</script>

You can't inline Ruby code into .js files. If you want to use Ruby code, you need to create a .js.erb file and then render a partial inside of that.
# controller
render :partial => "/path/to/js/partial.js.erb"
# inside your JS partial
# you can use <%= #consumer.name %> freely in this file
# and then add the line below to render your normal html.erb file
$("#reviews").append("<%= escape_javascript(render(:partial => '/path/to/partial.html.erb' )) %>");

Related

Pass JavaScript variable to JSP session

I wrote a code to get client ip address from JavaScript. But i can't get proper output from that. i am getting error in this semicolon <% ; %>. I mentioned my code below. thank you.
<script>
function getMyIpAddress() {
$.getJSON("https://jsonip.com?callback=?", function(data) {
<%String ipAddress =%>data.ip; <% ; %>
//alert("Your IP address is :- " + data.ip);
//document.getElementById("demo").innerHTML = ipAddress;
<% session.setAttribute("clientipAddress", ipAddress); %>
});
}
</script>
The jsp is java servlet page.So in the <% %> or <% =%> should be java fragment code.
As you see,In you code <%String ipAddress =%> there just a variable declaration the ipAddress is null, the correct grammar is <%ipAddress=%>,and the <% ; %> is wrong grammar in java too.

Importing header file in html file is not working properly

I have a header.html and header.js files because I want to use the same header through my webpages.
In header.js file, on window load I want it to console.log("header file loaded").
I also have index.html and index.js file for my homepage. In index.js, on window load I want it to console.log("index file loaded")
I called header.html in index.html file, in order to import the header for the homepage. This works fine.
based on js files the console output should
header file loaded
index file loaded
The problem I am having is that
it seems like header.js and index.js cannot work simultaneously
only the last referenced file gets outputed in the console
for example this format
<script src="js/header.js"></script>
<script src="js/index.js"></script>
will output
index file loaded
and this
<script src="js/index.js"></script>
<script src="js/header.js"></script>
will output
header file loaded
I use the code to import header.html in index.html
<head>
<div data-include="header"></div>
</head>
<body>
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
</body>
this is the content of both js file
function retrieveInfo(data) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Sellers/' + userId).once('value').then(function(snapshot) {
console.log(userId)
console.log("index file loaded")
});
}
})
}
what am I doing wrong and how can I fix it to have both js file called?
You are doing it in a wrong way, .load() is used for loading HTML contents. You should be using .getScript(), to load the js and execute it.
According to docs:
.load()
Load data from the server and place the returned HTML into the matched element.
.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Here is an example for using getScript:
$.ajax({
url: url,
dataType: "script",
success: function() {
alert("script loaded");
}
});
In your case it would be:
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var JS = $(this).data('include') + '.js';
var file = $(this).data('include') + '.html';
$(this).load(file);
$.ajax({
url: JS,
dataType: "script",
success: function() {
alert(file + " loaded");
}
});
});
});

Confirm Delete Javascript message not getting displayed on 'IE11' and 'Chrome'

I have confirm delete message in my application and it works on IE8-9 but not on 'IE11' and 'Chrome'. I checked all settings and scripts are enabled on both browsers.
When I click on 'delete' link nothing happens page is just refreshed and no message is displayed and record is not deleted.
This is my _delete_from_page.rhtml file in 'views' directory.
<%= render :partial => "layouts/top_menu"%>
<%= render :active_scaffold => "testing_page_chain"%>
<html>
<head>
<script language="javascript">
function doRedirect()
{
var confirm_msg=confirm("Are you sure you want to delete the request with ID <%=#d.controller_id%>?" ,"");
var id=<%=#d.id%>
if (confirm_msg==true)
{
window.location="<%= url_for(:controller => "#{params[:controller]}")%>/confirm_delete?id="+id;
}
else
{
window.location="<%= url_for(:controller => "#{params[:controller]}")%>/cancel_delete";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
</script>
</head>
</html>
<script language="javascript" type="text/javascript">
window.onload=addLoadEvent(doRedirect)
</script>
and I call this from controller 'testing_page_chain_controller.rb' like
render :partial => "delete_from_page"
Why don't you use data-confirm?
<%=link_to 'Delete', url, date: {confirm: 'Are you sure?'} %>
This is in Rails default installation by default. Then you can do your server stuff after they confirm they want to delete the object.

Get a javascript value to a ruby value

I am trying to use Aviary API in my ruby on rails site. I have trouble to get back the URL created by Aviary in the onSave function. I don't know how to access it in ruby. Do you have an idea?
The variable i would like to have in ruby is newURL
<% if #photo.image? %>
<!-- Load widget code -->
<script language="JavaScript" type="text/javascript" src="https://dme0ih8comzn4.cloudfront.net/js/feather.js"></script>
<!-- Instantiate the widget -->
<script type="text/javascript">
var featherEditor = new Aviary.Feather({
apiKey: ' f20374413e3ff5a8',
apiVersion: 2,
theme: 'light',
tools: 'all',
appendTo: '',
fileFormat: 'jpg',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
<!-- Add an edit button, passing the HTML id of the image and the public URL to the image -->
<a href="#" data-refresh="true" onclick="return launchEditor('editimage1',
'<%= #photo.image.url %>');">Edit!</a>
<img id='editimage1' src='<%= #photo.image.url %>' height="352" width="470"/>
<% end %>

Javascript File References Problem (with jQuery)

Before, I had this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
Line: 54
Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong?
Am I right in saying that this is ASP.Net? If it is, inline scripts like:
<%=Url.Action("GetDescription") %>
cannot go in the external JavaScript file.
Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -";
Since you are now serving the js as a static file, rather than via your ASP, lines like
<%=Url.Action("GetChildCategories") %>
will no longer work as the server doesn't interpret them and replace them with the correct values. You'll need to hard-code them in the script, or leave those lines as inline scripts in the main page and set them as global variables which you can then reference from the external file.

Categories