How to translate into other languages my web page? - javascript

How can I translate my web pages? Actually what technology or what scripting-if require- should be used? For info; I have all translated text. But I do not want to create something like clone site for other language.
I used just javascript -including jquery .

Just using JavaScript...
<script type="text/javascript">
// JSON-formatted, potentially read from a database
var article = {
title: {
en_US: "Article Title",
fr_FR: "Titre de l\'Article"
},
content: {
en_US: "Content of the Article.",
fr_FR: "Contenu de l\'Article."
}
}
// simple function to write the info to the page
function get_i18n(item, lang) {
document.write(article[item][lang]);
}
</script>
<!-- English Version -->
<div class="story">
<h1 class="title"><script>get_i18n('title','en_US');</script></h1>
<p class="content"><script>get_i18n('content','en_US');</script></p>
</div>
<!-- French Version -->
<div class="story">
<h1 class="title"><script>get_i18n('title','fr_FR');</script></h1>
<p class="content"><script>get_i18n('content','fr_FR');</script></p>
</div>
Please Note: This isn't a very graceful solution. I'm sure there's a prettier method...

You actually mean "how to build multi lingual website" as you already have the "translated text" as you call it.
One way is to put the text inside containers then using client side code change the containers contents to the proper text according to selected language, having arrays with translated text in each language.
If you have server side language at your disposal it would be much better though - do you have such thing?

Using CSS attribute selectors:
<style type="text/css">
// hides all French blocks by default
div.story[lang="fr"] {
display: none;
}
// hide all English blocks
body[lang="fr"] div.story[lang="en"] {
display: none;
}
// show all French blocks
body[lang="fr"] div.story[lang="fr"] {
display: block;
}
</style>
<!-- Change this to the language of the blocks you want to display -->
<body lang="fr">
<!-- English block, shown by default -->
<div class="story" lang="en">
<h1 class="title">Article Title</h1>
<p class="content">Content of the Article.</p>
</div>
<!-- French block, hidden by default -->
<div class="story" lang="fr">
<h1 class="title">Titre de l'Article</h1>
<p class="content">Contenu de l'Article.</p>
</div>
</body>
This setup defaults to showing all English blocks, unless lang="fr" is set on the <body> tag.
Of course, you'll still need some way to modify the lang attribute of the <body> tag...

It would take too long for JavaScript to translate your site. I'd say find some software that can translate HTML files and keep both versions on your server. I know this isn't what you want, but it's the only practical way right now.

You can use Cloud Translation, it's a free and open-source project from Angry Monkey Cloud: https://github.com/angrymonkeycloud/CloudTranslation.
You should add a reference to jQuery first, then to the CloudTranslation JavaScript file:
<script crossorigin="anonymous" src="https://cdn.amcapi.com/translation/cloudtranslation-1.0.0.min.js"></script>
And add the configuration within the HTML head as follows:
<script type="application/json" id="CloudTranslationConfig">
{
"Settings": {
"DefaultLanguage": "en",
"TranslatorProvider": "Azure", // not required if you filled in all translations
"TranslatorProviderKey": "{Your Microsoft Azure Translator Key}", // not required if above is empty
"UrlLanguageLocation": "Subdirectory"
},
"Languages": [
{
"Code": "en",
"DisplayName": "English"
},
{
"Code": "ar",
"DisplayName": "Arabic",
"Direction": "rtl"
}
],
"Translations": [
{
"en": "Home",
"ar": "الصفحة الرئيسية"
},
}
</script>
and add your own custom select (dropdown) having the class "CloudTranslationSelect" (you can customize the style of your select the way you want).
More information found on https://www.angrymonkeycloud.com/translation

I have improved the first answer a bit. Just use a function to set the lanaguage value in localStorage and then get the language from there and dynamically change the HTML with the global variable lgn.
<script type="text/javascript">
// JSON-formatted, potentially read from a database
var article = {
title: {
en_US: "Article Title",
fr_FR: "Titre de l\'Article"
},
content: {
en_US: "Content of the Article.",
fr_FR: "Contenu de l\'Article."
}
}
// simple function to write the info to the page
function get_i18n(item, lang) {
document.write(article[item][lang]);
}
var lng; //global variable
if (localStorage.getItem('lng') == null) { //if I have no language saved just load the English language
lng = 'en_US';
localStorage.setItem('lng', lng);
}
if(localStorage.getItem("lng") == 'en_US'){
lng = 'en_US';
}
if(localStorage.getItem("lng") == 'fr_FR'){
lng = 'fr_FR';
}
console.log(lng);
function get_i18n(item, lng) {
document.write(article[item][lng]);
}
</script>
<div class="story">
<h1 class="title"><script>get_i18n('title',lng);</script></h1>
<p class="content"><script>get_i18n('content',lng);</script></p>
</div>

Related

Ho can get values from Quill editor form for my php code? [duplicate]

I have what I think is a very common scenario. I would normally have this form:
<form method="post">
<textarea name="text"></textarea>
<input type="submit" value="Save" />
</form>
Then with PHP I would capture the data from the form ($_POST['text']) and I could use that in another variable.
Now, I'd like to use Quill so users have a nice rich text editor instead. Quill seems very well suited for this and the documentation is very detailed. However, for some reason I can not find how I can "post" the data to the form. There is one single sample page that sort of does what I want, but I am unable to fully implement this in my sample, and in the quick start guide this rather fundamental (to me) topic is not discussed, and I can not find this in the documentation either.
Is Quill supposed to be used like this? Am I overseeing something? Is there a recommended way to make this work?
This is what I currently have:
<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">
</head>
<body>
<form method="post">
<!-- Create the toolbar container -->
<div id="toolbar">
<button class="ql-bold">Bold</button>
<button class="ql-italic">Italic</button>
</div>
<form method="post">
<!-- Create the editor container -->
<div id="editor">
<p>Hello World!</p>
</div>
<input type="submit" value="Save" />
</form>
<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script>
<!-- Initialize Quill editor -->
<script>
var editor = new Quill('#editor', {
modules: { toolbar: '#toolbar' },
theme: 'snow'
});
</script>
</body>
</html>
<form method="post" id="identifier">
<div id="quillArea"></div>
<textarea name="text" style="display:none" id="hiddenArea"></textarea>
<input type="submit" value="Save" />
</form>
If you give the form an identifier, then using jQuery you can do the following:
var quill = new Quill ({...}) //definition of the quill
$("#identifier").on("submit",function() {
$("#hiddenArea").val($("#quillArea").html());
})
Instead of the HTML you could use quill.getContents() to get the delta.
You can check related discussion about it https://github.com/quilljs/quill/issues/87
While this is not an ideal solution :
var myEditor = document.querySelector('#editor')
var html = myEditor.children[0].innerHTML
Here's the code I used to do this:
$(document).ready(function(){
$("#theform").on("submit", function () {
var hvalue = $('.ql-editor').html();
$(this).append("<textarea name='content' style='display:none'>"+hvalue+"</textarea>");
});
});
Basically, what it does is to add a hidden textarea to your form and copy the content of the "ql-editor" container (This is automatically made by Quill Editor in the container div) to it. The textarea will then be submitted with the form. You need to change the IDs used in the code to the id of your container tags.
I'm doing this:
var quill = new Quill('.quill-textarea', {
placeholder: 'Enter Detail',
theme: 'snow',
modules: {
toolbar: [
['bold', 'italic', 'underline', 'strike'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'indent': '-1'}, { 'indent': '+1' }]
]
}
});
quill.on('text-change', function(delta, oldDelta, source) {
console.log(quill.container.firstChild.innerHTML)
$('#detail').val(quill.container.firstChild.innerHTML);
});
Somewhere on the form:
<div class="quill-textarea"></div>
<textarea style="display: none" id="detail" name="detail"></textarea>
A solution I came up with was to make a wrapper class.
class QuillWrapper {
/**
* #param targetDivId { string } The id of the div the editor will be in.
* #param targetInputId { string } The id of the hidden input
* #param quillOptions { any } The options for quill
*/
constructor(targetDivId, targetInputId, quillOptions) {
//Validate target div existence
this.targetDiv = document.getElementById(targetDivId);
if (!this.targetDiv) throw "Target div id was invalid";
//Validate target input existence
this.targetInput = document.getElementById(targetInputId);
if (!this.targetInput) throw "Target input id was invalid";
//Init Quill
this.quill = new Quill("#" + targetDivId, quillOptions);
//Bind the two containers together by listening to the on-change event
this.quill.on('text-change',
() => {
this.targetInput.value = this.targetDiv.children[0].innerHTML;
});
}
}
Simply include the class somewhere on your page and then use the following to initilize it:
let scopeEditor = new QuillWrapper("ScopeEditor", "Scope", { theme: "snow" });
Your html would look roughly like this:
<div class="form-group">
<label asp-for="Scope" class="control-label col-md-2"></label>
<div id="ScopeEditor"></div>
<input type="hidden" asp-for="Scope" class="form-control" />
</div>
I know this problem has already been resolved, but I would like to add a little more information. To obtain the data present in Quill, You don't need jQuery, or a different trick. I recommend looking at this answer:
https://stackoverflow.com/a/42541886/2910546
I should also make a note here: The author's question was asked at least 2 years ago. So, today, I believe this is to be the most viable way to address the question.
For more information on Quill, with case study examples, and common questions with answers, please kindly visit the following link:
https://github.com/loagit/Quill-Examples-and-FAQ
this is what i use, all you have to do is to provide data-name attribute to your editor tag. this will create a hidden input as sibling to your editor tag and put the html contents inside. you can get other formats of your contents, i leaved unused variables if you need to know how to get them.
html:
<div class="field editor" data-name="experience"></div>
js:
let quill_element = document.querySelector('.editor')
let quill = new Quill(quill_element, {
modules: {
toolbar: '#toolbar'
},
placeholder: document.querySelector('.editor').getAttribute('data-placeholder'),
theme: 'bubble',
});
let hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = quill_element.getAttribute('data-name');
quill_element.parentElement.appendChild(hiddenInput);
quill.on('text-change', function () {
let justHtml = quill.root.innerHTML;
hiddenInput.value = justHtml;
// other formats if you like to use..
var delta = editor.getContents();
var text = editor.getText();
});
Solved here
How to save Quill.js values to Database Laravel 5.6
Add a hidden input :
<input type="hidden" name="body"/>
Js code :
var form = document.getElementById("FormId");
form.onsubmit = function() {
var name = document.querySelector('input[name=body]');
name.value = JSON.stringify(quill.getContents());
return true; // submit form
}
To set contents to quill do this :
quill.setContents({!! $post->body !!});
I found that prevoius solutions on the page also copied a lot of quiill markup html at the end of the field when copied to a hidden field.
The solution described on this page seems to recitfy that:
https://lucidar.me/en/rich-content-editor/how-to-get-html-content-from-quill-rich-editor/
Basically, access the pure HTML with:
var html = quil.root.innerHTML
document.getElementById("descriptionHidden").value = html;
Try this:
<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<!-- Initialize Quill editor -->
<script>
var quill = new Quill('#editor', {
modules: {
toolbar: [
['bold', 'italic'],
['link', 'blockquote', 'code-block', 'image'],
[{
list: 'ordered'
}, {
list: 'bullet'
}]
]
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
$("#form").submit(function() {
$("#description").val(quill.getContents());
});
</script>
this solution works fine for me:
<script type="text/javascript">
$(document).ready(function(){
$("#emailForm").on("submit", function () {
var hvalue = $('.editor').text();
$(this).append("<textarea name='message' style='display:none'>"+hvalue+"</textarea>");
});
});
</script>
I solved this problem as follows.
In the element that will be the editor's container, I set a like attribute, data-input-name="something"
and after instantiating the editor I just made a simple code that assigns the internal value of the quill to hidden input
quill.on('text-change', function() {
const content = quill.root.innerHTML.trim();
const targetId = quill.container.dataset.inputName
document.querySelector(`#${targetId}`).setAttribute("value", content);
});
Checkout this repo, it might be helpful. It's easy to install.
https://github.com/tangien/quilljs-textarea
AutoInitialize Quilljs simply by adding the attribute data-quilljs to the textarea element and the rest the plugin will take care of it.
Thats it!
Link CSS:
<!-- CSS Implementing Plugins -->
<link rel="stylesheet" href="https://htmlstream.com/preview/front-v4.2/html/assets/css/vendor.min.css">
<link rel="stylesheet" href="https://htmlstream.com/preview/front-v4.2/html/assets/vendor/bootstrap-icons/font/bootstrap-icons.css">
<!-- CSS Front Template -->
<link rel="stylesheet" href="https://htmlstream.com/preview/front-v4.2/html/assets/css/theme.min.css?v=1.0">
Link JS:
<!-- JS Implementing Plugins -->
<script src="https://htmlstream.com/preview/front-v4.2/html/assets/js/vendor.min.js"></script>
<!-- JS Front -->
<script src="https://htmlstream.com/preview/front-v4.2/html/assets/js/theme.min.js"></script>
En mi html:
<form id="form-perfil" name="form-perfil" method="POST">
<!-- Form Group -->
<div class="row form-group">
<label class="col-sm-3 col-form-label input-label">BIO</label>
<div class="col-sm-9">
<!-- Quill -->
<div class="quill-custom">
<div
class="js-quill"
style="min-height: 15rem;"
data-hs-quill-options='{
"placeholder": "Type your message...",
"modules": {
"toolbar": [
["bold", "italic", "underline", "strike", "link", "image", "blockquote", "code", {"list": "bullet"}]
]
}
}'
>
Creative mind at Htmlstream
</div>
</div>
<!-- End Quill -->
<textarea name="text_quill" style="display: none;" id="text_quill"></textarea>
</div>
</div>
<!-- End Form Group -->
<button type="submit" class="mt-3 float-right btn btn-primary">Enviar formulario</button>
<!-- End Form Group -->
</form>
En mi JS:
// INITIALIZATION OF QUILLJS EDITOR
// =======================================================
var quill = $.HSCore.components.HSQuill.init('.js-quill');
// =======================================================
$("#form-perfil").on("submit", function (e) {
e.preventDefault(); //No se activará la acción predeterminada del evento
$("#text_quill").val($(".ql-editor").html());
var formData = new FormData($("#form-perfil")[0]);
$.ajax({
url: "ajax/pago_administrador.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (datos) { },
});
});

Highlight specific word from similar words string

There are some similar words in a string and I need to highlight only one word out of it. I have index value of this specific word. I'm using Mark JS for this. I need to do this in filter part of mark JS function. But not sure how will I get index value of each word while filtering.
Here is the fiddle to test
Code JS
$(function() {
$content = $(".content"),
currentIndex = 0;
var indexVal = 40;
$('#markBtn').on("click", function() {
var searchVal = " ipsum ";
$content.unmark({
done: function() {
console.log("unmark")
$content.mark(searchVal, {
"element": "span",
"className": "mark",
"accuracy": "partially",
"iframes": true,
"ignoreJoiners": true,
"acrossElements": true,
"separateWordSearch": true,
"diacritics": false,
"filter": function (textNode, foundTerm, totalCounter, counter) {
console.log("marks - filter " + textNode+" "+foundTerm);
//check indexVal with foundTerm and return true
return true;
},
"each": function (node) {
console.log("marks - each " + node);
},
"done": function() {
console.log("marks - done ");
}
});
}
});
});
});
HTML
<div class="header">
Mark second word 'ipsum' in the text below.
<button id="markBtn">Mark Text</button>
</div>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur ipsum adipiscing elit ipsum.</p>
</div>
Refer this Link.
it may help u
http://jsfiddle.net/sadhique92/HfS7e/1231/
<script>
function highlightSearch() {
var text = document.getElementById("query").value;
var query = new RegExp("(\\b" + text + "\\b)", "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>$1</span>");
document.getElementById("searchtext").innerHTML = newe;
}
</script>
<style>
#searchtext span{
background-color:#FF9;
color:#555;
}
div {
padding: 10px;
}
</style>
<div><h2>Find and highlight text in document</h2>
<form action="" method="" id="search" name="search">
<input name="query" id="query" type="text" size="30" maxlength="30">
<input name="searchit" type="button" value="Search" onClick="highlightSearch()">
</form></div>
<div id="searchtext">
<p>JavaScript is the programming language of the Web. The overwhelming majority of
modern websites use JavaScript, and all modern web browsers—on desktops, game
consoles, tablets, and smart phones—include JavaScript interpreters, making Java-
Script the most ubiquitous programming language in history. JavaScript is part of the
triad of technologies that all Web developers must learn: HTML to specify the content
of web pages, CSS to specify the presentation of web pages, and JavaScript to specify
the behavior of web pages. This book will help you master the language.</p>
<p>If you are already familiar with other programming languages, it may help you to know
that JavaScript is a high-level, dynamic, untyped interpreted programming language
that is well-suited to object-oriented and functional programming styles. JavaScript
derives its syntax from Java, its first-class functions from Scheme, and its prototypebased
inheritance from Self. But you do not need to know any of those languages, or
be familiar with those terms, to use this book and learn JavaScript.</p>
<p>The name "JavaScript" is actually somewhat misleading. <span>Except</span> for a superficial syntactic
resemblance, JavaScript is completely different from the Java programming language.
And JavaScript has long since outgrown its scripting-language roots to become
a robust and efficient general-purpose language. The latest version of the language (see
the sidebar) defines new features for serious large-scale software development.</p>
</div>
The filter should return the current index that you want to mark:
"filter": function (textNode, foundTerm, totalCounter, counter) {
console.log("marks - filter " + textNode+" "+foundTerm);
var result = totalCounter == currentIndex;
return result;
},
so if you put currentIndex = 0 it will select the first matching and so on ...
Your question: not sure how will I get index value of each word while filtering?
The Mark JS documentation read as follows:
filter function: A callback to filter or limit matches. It will be called for each match and receives the following parameters:The text node which includes the matchThe term that has been foundA counter indicating the total number of all marks at the time of the function callA counter indicating the number of marks for the termThe function must return false if the mark should be stopped, otherwise true.
In order words: the for forth parameter is the counter(index) of each word found.

Image Gallery hosted in Google Drive Folder

I've been looking for a way to create a gallery on a website with images from a folder in my google drive. Which I have shared here: https://drive.google.com/drive/u/0/folders/0Bwx-OwnNeIvwRldSVlU5SGN0dGs
inside it is a simple HTML, and a gallery folder with pictures of monster trucks and cute animals. And the goal is here to create a gallery where people can upload images of well; monster trucks and cute animals.
I've been searching for all kinds of methods of achieving this and this is what I have found so far:
In short what I am trying to achieve is to get the id's of images in a publicly shared folder in my G-Drive. Then use those id's to create a gallery via JS in an HTML.
What my HTML looks like now:
index.html
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<!-- all divs will append here -->
</div>
What I researched on the Drive SDK:
I've been using the "try it" section here to figure out what i need to do. https://developers.google.com/drive/v2/reference/children/list#examples
Request result: GET https://www.googleapis.com/drive/v2/files/0Bwx-OwnNeIvwRG5rNzZ6OURSNEk/children?fields=items%2Fid
Response result:
200 OK
- SHOW HEADERS -
{
"items": [
{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
},
{
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
},
{
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
},
{
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
},
{
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
},
{
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]}
What I would like for the script to do:
script.js
var imageIds = <!-- ids from the the response --> ;
var x = imageIds.length;
for (var i = 0; i < x; i++) {
<!-- create a <div> -->
}
//See below*
Create a div: In the for loop it will create a <div> with a specific "class" and an <img> inside that div, with a "src="http://drive.google.com/uc?export=view&id=IMAGE-ID" where the "IMAGE-ID" was gotten from the "Response". the <div> will then be appended to <div id="gallery"> in the index.html.
What I would like for the end HTML do look like:
index.html:
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwaFZXVzVmMl9ILUU">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwVk1DTEpnR0J6VHc">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwblBHLVEza0hxY2s">
</div>
<!-- and so on ... -->
</div>
What I am unsure of now, is how this needs to be authenticated to get the image-ids from the G-Drive folder. This could be hosted from Google Drive itself with their hosting links, or it could be created through Google Apps Script, and the functionality to serve HTML there, and that would make the authentication easier as you can get everything from drive directly.
I don't understand why this is no where to be found, that does not involve a payment. It would be great if everyone had the opportunity to create image galleries from images in a G-Drive folder.
Would really like your help on this one. Thanks alot.
Firstly, about the code itself, it would be something like that:
document.addEventListener('DOMContentLoaded', function() {
var response = {
"items": [{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
}, {
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
}, {
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
}, {
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
}, {
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
}, {
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]
};
var imageIds = response.items.map(function(item) {
return '<div class="brick"><img src="http://drive.google.com/uc?export=view&id=' + item.id + '"></div>';
});
document.getElementById('gallery').insertAdjacentHTML('afterbegin', imageIds.join(''));
});
<div id="gallery"></div>
About the authorization, take a look at their documentation.

Parsing Dynamic JSON Generated From Website (CoovaChilli) And Display It Into Javascript Webpage?

i really need your help to help me solving my problem. I setup a captive portal using CoovaChilli, and want to show the usage feedback provided by Coova JSON Interface that can be accessed via url like this http://login.domain.com:3990/json/status from the internal network where the CoovaChilli listen on. If you already logged in into the captive portal and then if you access that url you will see data formated like this in your browser:
{
"version": "1.0",
"clientState": 1,
"redir": {
"originalURL": "http://www.gstatic.com/generate_204",
"redirectionURL": "",
"logoutURL": "http://10.1.0.1:3990/logoff",
"ipAddress": "10.1.0.6",
"macAddress": "AA-BB-CC-DD-EE-FF"
},
"session": {
"sessionId": "5108c39600000003",
"userName": "user#ri",
"startTime": 1359529249,
"sessionTimeout": 0,
"idleTimeout": 900
},
"accounting": {
"sessionTime": 867,
"idleTime": 0,
"inputOctets": 1428643,
"outputOctets": 391752,
"inputGigawords": 0,
"outputGigawords": 0,
"viewPoint": "client"
}
}
My question is, what should i do if want to parsing that data into a webpage using *Javascript* so i can see that data formatted more nicely (html formatted). For example i can access it via url using same domain like this http://login.domain.com/status/status.html rather than unformatted data in the previous url ?
Please note : i want use javascript to parsing because the data is different by the user who logged in into that CoovaChilli, different user have different data, only user who logged in and accessing that url can see only their own statistic, so i think the best practice is use a client side language to parsing that data.
Any of your help is very appreciated. Thank you before.
Try this
This link may help you http://www.w3schools.com/json/json_intro.asp
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p>
Name: <span id="jname"></span><br>
Age: <span id="jage"></span><br>
Address: <span id="jstreet"></span><br>
Phone: <span id="jphone"></span><br>
</p>
<script>
var JSONObject = {
"name":"John Johnson",
"street":"Oslo West 16",
"age":33,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
</body>
</html>
Edit
If you want to remove var json you can use ajax or jquery
eg:
$.getJSON("your url",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
http://www.w3schools.com/jquery/ajax_getjson.asp
<script src="js/jquery.min.js"></script>
<script>
$.getJSON("http://10.1.0.1:3990/json/status?callback=?", function(data) {
console.log(data);
});
</script>

What is the missing puzzle piece to exporting images from FusionCharts?

I am trying to get FusionCharts to export.
I have, besides XML files that specify registerWithJS="1",
<script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>
<script type="text/javascript" src="FusionCharts/FusionChartsExportComponent.js"></script>
and
<div class="portlet" id="recent-portfolio-trends">
<div title="View graphs and charts of your portfolio." class="portlet-header">Recent Portfolio Trends</div>
<div class="portlet-content">
<!-- Trends -->
<span id="Trends-OS">FusionCharts will load here!</span>
<span id="Trends-Vol">FusionCharts will load here!</span>
<div id="fcexpDiv">FusionCharts Export Handler Component</div>
<div id="fcexpDiv2">FusionCharts Export Handler Component 2</div>
<script type="text/javascript">
var myChart = new FusionCharts( "FusionCharts/MSColumn2D.swf", "column", "350", "220", "0", "1" );
myChart.setXMLUrl("FusionCharts/trends-outstandings.xml");
myChart.render("Trends-OS");
var myExportComponent = new FusionChartsExportObject("fcExporter1", "FusionCharts/FCExporter.swf");
myExportComponent.debugMode = true;
myExportComponent.exportAttributes.exportAtClient = '1';
myExportComponent.exportFilename = "Outstanding";
myExportComponent.render("fcexpDiv");
</script>
<script type="text/javascript">
var myChart = new FusionCharts( "FusionCharts/MSCombi2D.swf", "column", "350", "220", "0", "1" );
myChart.setXMLUrl("FusionCharts/trends-volume.xml");
myChart.render("Trends-Vol");
var myExportComponent2 = new FusionChartsExportObject("fcExporter2", "FusionCharts/FCExporter.swf");
myExportComponent2.debugMode = true;
myExportComponent2.exportAttributes.exportAtClient = '1';
myExportComponent.exportFilename = "Volume";
myExportComponent2.render("fcexpDiv2");
</script>
Google searching suggests in various forms that I need to specify registerWithJS to be "1", perhaps in more than one place, and that I should get a diagnostic error code in an alert with debugMode set to True. (I do not get an alert or anything on Chrome's JavaScript console.) This is being served up by a distinct web server, so it's not a "local filesystem protection" issue.
What I do get are two charts rendered properly, plus two buttons that say "Waiting" and never, at least after a few minutes, change to say anything else. If I right-click the graphs, the contextmenu offers "Print Chart", "Copy data to clipboard", "About FusionCharts", "Settings...", "Global Settings...", and "About Adobe Flash Player 10.3.181.14..." but not the options to export as JPG, PNG, or PDF that should be available.
Suggestions for what I need to do?
You would need to set at-least three export related XML attributes in your XML to enable the export related context menu. These are : exportEnabled, exportAtClient and exportHandler.
Hence, your trends-outstandings.xml would contain:
<chart exportEnabled='1' exportAtClient='1' exportHandler='fcExporter1' ...>
and trends-volume.xml would contain:
<chart exportEnabled='1' exportAtClient='1' exportHandler='fcExporter2' ...>
Also please make sure you are using the latest FusionCharts.js and FusionChartsExportComponent.js.
Please try setting exportEnabled='1'

Categories