I'm trying to get a json response from a rails controller and insert it into a js function. I keep getting errors:
MY CONTROLLER
def live #users present or attendees view
@presentation = Presentation.find(params[:secret])
@countdown = @presentation.start - DateTime.now()
#IF A PERSON IS A PRESENTER
if @presentation.presenter.id == current_user.id
@presenter = true
require 'json'
require 'net/http'
require 'uri'
uri = URI.parse('https://api.screenleap.com/v2/screen-shares')
req = Net::HTTP::Post.new(uri.path, initheader = {'accountid' => 'APPID', 'authtoken' => 'MYTOKEN'}) #These are correct in actual code
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
res = http.request(req)
@screenShareData = JSON.parse(res.body)
#IF A PERSON IS AN ATTENDEE
else
@presenter = false
@screenShareData = false
end
end
IN MY VIEW
<script>
<script type="text/javascript" src="https://api.screenleap.com/js/screenleap.js"></script>
window.onload = function() {
var callbacks = {
nativeDownloadStarting: [onNativeDownloadStartCallback],
screenShareStarting: [onScreenShareStarting],
appConnectionFailed: [onAppConnectionFailed],
screenShareStartError: [onScreenShareStartError]
};
var screenShareData = <%= @screenShareData %>;
var presenterAppType = 'NATIVE';
screenleap.startSharing(presenterAppType, screenShareData, callbacks);
};
</script>
In my view I also tried:
var screenShareData = <%= @screenShareData.to_s.html_safe %>;
In either case I seem to get one of two javascript errors. Either "Uncaught SyntaxError: Unexpected token &" or "Uncaught SyntaxError: Unexpected token =>"
My feeling is that it's somehow not translating the JSON the way the function expects it. Any idea how I might fix the issue?
@screenShareData = JSON.parse(res.body)parsing the JSON data and storing as Hash? Either you do not parse it at all or convert it to JSON using.to_jsonmethod.jsonresponse from your controller, tryconsole.log(screenSharedData)to see what you got.