How to send json string from backing bean to external javascript file? - json

i have external javascript file for drawing google charts
and in this js file i want to access backing bean to get json string.
js file:
window.onload = function(){
if(typeof(google)!= undefined){
google.load('visualization', '1.0', {'packages':['corechart'],callback: drawChart});
}
};
function drawChart() {
var jsonStr=#{myBean.jsonStr} // i want to be able to do something like that
var data_recSent = new google.visualization.DataTable(jsonStr);
//
//
}
if there's no possible solution/workaround for this case, please advise about other solutions.

best solution i have found so far, is to store the json string in hidden input, and then get the value of this hidden input in the js file.

If the result of #{myBean.jsonStr} is big, I would suggest you to make it cached by browser as follows:
Use a separated js file to keep this json:
myjson.js
var jsonStrGobal=JSON_PLACEHOLDER;
In the html header
<script language="javascript" type="text/javascript" src="myjson.js?version=#{myBean.jsonVersion}" />
myjson.js is not stored physically, but loaded by a servlet or a backing bean, JSON_PLACEHOLDER is replaced by your json, this servlet of backing bean will set the Cache-control on http response header to make browser cache it. Servlet can be registered in web.xml, backing bean can be declared in pages.xml as a page action.
Increase myBean.jsonVersion whenever the content of json changes so that browser gets notified.

Related

Updating automatically an HTML content when the imported *.json values are changed

I have an HTML code that imports a LOCAL but UPDATABLE *.json content, and it must be updated automatically when the *.json file is updated.
This is the *.HTML code:
<html>
<head>
<script type="text/javascript" src="sample.json"></script>
<script type="text/javascript" >
function load() {
setInterval(function () {
var mydata = JSON.parse(data);
var div = document.getElementById('data');
div.innerHTML = mydata[0].location.altitude;
}, 100);}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
and the adapted sample.json file is:
data = '[{"location": {"altitude": 40}}]';
I just wanna see the altitude is changing in the browser(HTML) whenever the sample.json file is updated.
Now the HTML works but only ONCE, I wanna make it dynamic.
What should I do to make the function setInterval work correctly? or maybe this function works only for local changes, not external ones.
Thnks, Sadeq
If you want the browser to get data from a URL even interval, then you need to write code which gets data from a URL in the interval. e.g. with the Fetch API. (At which point you should make it JSON instead of JS).
However HTTP is not fast. You do not want to be polling over HTTP every 100ms. Consider using Websockets to push the data from the server when it changes instead of polling.

how to send a Json object to a dialog from the parent using dialog API in Office365

I am new to office 365 word JavaScript API. I am trying to send a Json object to a dialog from the parent using the dialog api. But I couldn't find a better solution for that. I have found it is possible to send a Json object from the dialog to the parent using below code snippet.
Office.context.ui.messageParent
can someone give me a good solution with a code snippet to solve this problem?
You can try something like that
In parent web page (the actual add-in) javascript code
Office.context.ui.displayDialogAsync(url, options, function(result) {
var dialog = result.value;
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function(args){
dialog.close();
var json = JSON.parse(args.message);
//do what ever you need to do...
});
});
NOTE: for the sake of simplicity I omitted "error checks" if callback function receive error result. You should take care of that as well.
The web page that is opened at url will have a function for pushing back the json object after representing it as a string
var asString = JSON.stringify(myObj);
Office.context.ui.messageParent(asString);
Of course the webpage opened in the dialog window must also reference Office.js.
Here is the documentation link for this so-called dialogAPI https://dev.office.com/reference/add-ins/shared/officeui
Edit:
the original question is to send data from parent to children
If you need to send info to the page opened in dialogAPI. I suggest your append query parameters to url. You can stringify your Json object and pass it. This is not very clean thought.
Standardized way to serialize JSON to query string?
You can send JSON data or object back to your parent easily.
This code snippet should be in your child page's(Dialog page) JS file.
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
$('#btnLogin').click(submit);
});
};
function submit() {
// Get and create the data object.
var email = $('#txtEmail').val();
var password = $('#txtPassword').val();
var data = {
email: email,
password: password
}
// Create the JSON and send it to the parent.
var json = JSON.stringify(data);
Office.context.ui.messageParent("json");
}
})();
See here: https://dev.office.com/docs/add-ins/develop/dialog-api-in-office-add-ins
Find section "Passing information to the dialog box".
Two primary ways:
Add query parameters to the URL
Store the information somewhere that is accessible to both the host window and dialog box, e.g. local storage

Handlebars Js Not Loading my Content

I am trying to parse some json with Handlebars on my website. I don't get any errors but also don't get any content. I've developed my own rest point to return a json response and I think my problem might be there somewhere, but you can see the response in the code.
http://codepen.io/anon/pen/Czdxh
$(document).ready(function(){
var raw_template = $('#post-template').html();
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Retrieve the placeHolder where the Posts will be displayed
var placeHolder = $("#all-posts");
// Fetch all Blog Posts data from server in JSON
$.getJSON("https://instapi-motleydev.rhcloud.com/liked",function(data){
$.each(data,function(index,element){
// Generate the HTML for each post
var html = template(element);
// Render the posts into the page
placeHolder.append(html);
});
});
});
Thanks for any help!
The problem was I was getting an array response from the server and needed to adapt my template to include the {#each this} syntax. Also switched my getJSON to a simple get and looped over the reaction that way and tossed the $.each handler.

Change html page with jqm (1.4.0), passing parameter

I am building several apps and want to be able to reuse som code as separate HTML pages by passing parameters to them.
I would really like to pass parameters via ajax with one of these:
Alt1
$.mobile.pageContainer.pagecontainer("change", "../Photo/Photo.html", { reload: true, parameter: "dummyParameter"});
$.mobile.changePage("../Photo/Photo.html", { reloadPage: true, parameter: "dummyParameter"});
Problem is that the page wont reload.
If I use the below link the page is loaded/reloaded, but I cant seem to find the passed parameter.
Alt2
Or through a basic link
(I would prefeer to not generate the url in javascript as in alt2 but if what it takes...)
I use this code to try to retreive the parameters:
$(document).on("pagebeforechange", function (e, data) {
if (data.toPage[0].id == "Photo") {
//var parameters = $(this).data("url").split("?")[1];
//var parameter = parameters.replace("paremeter=", "");
var stuff = data.options.stuff;
//showStuff("#p2", stuff);
}
});
While I'm at it, if someone uses type script. Visual studio complains about that this call signature isnt correct:
$(document).on("pagebeforechange", function (e, data)
Expects one argument, the event, not the data. The plugin generates correct javascript but the IDE complains.
Thanks!

JSON and passing a URL value as a parameter - Chrome Extension

Ok, this is my final tango with this. Below I've listed the code. I'm able to get the value of the url and display it on screen for the current (active tab) in Google Chrome. Now all I have to do is pass that value as a parameter in the URL via JSON. My processing file resides on a our remote server - in php. Everything I've done with respect to this has worked to perfection. However, any attempts to pass the current url or any url as one of the parameters - e.g. ?format=json&url=http://something.com&callback=? - results in nothing. I'm not sure if what I'm doing is wrong or if it is even possible. The important thing to note is that all we are looking to do is pass the url to a remote server for storage, processing etc and send back results. I have everything working but I just can't seem to get the url to pass as a parameter.
<html>
<head>
<title>API JSON Test</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var timeService =
"http://api.ulore.com/api2.php?key=abce&url="+tab.url+"&format=json&callback=?";
$.getJSON(timeService, function(data) {
$('#showdata').html("<p>url_results="+data.post.url+"</p>");
});
});
</script>
<div id="showdata"></div>
</head>
<body>
</body>
</html>
Again, all the JSON works fine when I'm testing other code. Even if I put in a NON-URL value as a parameter for url=..... it throws the appropriate error. However, it will not accept a URL for some reason.
Any feedback will be greatly appreciated.
Thanks,
Ethan-Anthony
Try encoding and decoding the url.
http://www.w3schools.com/tags/ref_urlencode.asp
http://php.net/manual/en/function.rawurlencode.php
http://phpjs.org/functions/rawurlencode:501