Home » Javascript » Rails application works in local environment but in production I can't call the function because its not defined

Rails application works in local environment but in production I can't call the function because its not defined

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a snippet that sends a http request to another site, but when it gets compiled in production I lose the ability to call on it and an undefined no method error. How do i make it so I can call the function from any page, without having to past it directly to every view that I want it at.

in my assets/javascript directory i have a ‘js file’ with the these lines

var foobar= {}    
foobar.report = function(eventName){
 var event = {event: {name:eventName}};
 var request = new XMLHttpRequest();
 request.open("POST", "http://localhost:3000/api/events", true)
 request.setRequestHeader('Content-Type', 'application/json');
 request.send(JSON.stringify(event));
};

then I have something like this to call it in the view

<script>foobar.report('about page loaded');</script>
Answers:

Place your code inside (function() {});

(function() {

var foobar= {}    
foobar.report = function(eventName){
 var event = {event: {name:eventName}};
 var request = new XMLHttpRequest();
 request.open("POST", "http://localhost:3000/api/events", true)
 request.setRequestHeader('Content-Type', 'application/json');
 request.send(JSON.stringify(event));
};`enter code here`




});