JavaScript/jQuery - Get text and translate it - javascript

Is it possible to use jQuery to get a text from an element and translate it to other languages?
Before
<p>Hello</p>
After
<p>bonjour</p>

Use this JQuery plugin
https://github.com/tinoni/translate.js
Disclaimer: I am the author
1 - Include the "trn" class to the text you want to translate:
<span class="trn">text to translate</span>
2 - Define a dictionary:
var dict = {
"text to translate": {
pt: "texto para traduzir"
},
"Download plugin": {
pt: "Descarregar plugin",
en: "Download plugin"
}
}
3 - Translate the entire page body:
var translator = $('body').translate({lang: "en", t: dict}); //use English
4 - Change to another language:
translator.lang("pt"); //change to Portuguese

Use Google translation API. Easy to use. The following translates Spanish to English. To translate from and to other languages, simply change 'es' and 'en'
<div id="content"></div>
google.load("language", "1");
function initialize() {
var content = document.getElementById('content');
content.innerHTML = '<div id="text">Hola, me alegro mucho de verte.<\/div><div id="translation"/>';
var text = document.getElementById("text").innerHTML;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
Check working example at http://jsfiddle.net/wJ2QP/1/

try google translate: http://code.google.com/apis/language/translate/overview.html

You can use Google Translate's Javascript API.
<p id="some">Hello</p>
<input id="trans" value="Translate" type="button">
<script>
$('#trans').click(function() {
google.language.translate($('#some').html(), 'en', 'fr', function(result) {
$('#some').html(result.translation);
});
});
</script>
You will need to load the js library in your page's HEAD section in order to use the API.

Use the Bing translator, since the free Google Translate API has been discontinued on December 1, 2011

On this PHP/JS solution you should use include PHP language files and set language on session/cookie not on $_GET. For the sake of simplicity I will do it on the
index.php file
<?php
$lang = $_GET['lang'];
if ($lang == 'fr'){
$w = array(
'Trouvé',
' non trouvé.',
'Erreur. Veuillez réessayer.'
);
}else if($lang == 'en'){
$w = array(
'Found',
' not found.',
'Error. Please try again.'
);
}else{
$w = array(
'Trouvé',
' non trouvé.',
'Erreur. Veuillez réessayer.'
);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
....................
<body>
....................
<script type="text/javascript">
/* Translate JS
Declare JS variables for translation in PHP file as below (Global vars outside $(document).ready).
Inside JS file call the variable as $.lang_mynamespace.var_name
*/
$.lang_scan = {
found_js:"<?=$w[0];?>",
not_found_js:"<?=$w[1];?>",
error_js:"<?=$w[2];?>"
};
</script>
</body>
</html>
JS file
$(function() {
$("#scan_result").on('change', function(){
//check number
$.ajax({
url: "check.php",
dataType: "json",
type: "post",
data: {'scan_no': scan_value} ,
success: function (response) {
if (response.status == true){
alert("Scan no. " + response.scan_no + $.lang_scan.found_js);
}else{
alert("Scan no. " + response.scan_no + $.lang_scan.not_found_js);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//ajax error
alert($.lang_scan.error_js);
}
});
});
});
check.php return a json
{"scan_no": "123", "status": true/false}

Why not try this:
var body = $("body");
var html = body.html();
var nhtml = html.split(" ");
var dict = [];
for (var i = 0; i < nhtml.length; i++) {
nhtml[i].replace(dict[index]);
}
It can replace anything.

Related

How to copy a div contenent to a txt file from a large html page

I need to copy the number of percent of the progress bar from this page to a txt file. (http://tienda.insidecraft.com/)
I have tried something like this:
$(document).on("ready", function() {
setInterval(querygoal, 5000);
querygoal();
$(".navbar-brand").tooltip({placement: "bottom", html: true});
$("[data-toggle='tooltip']").tooltip();
});
function querygoal() {
$.ajax({
url: "view-source:http://tienda.insidecraft.com/",
method: "GET",
success: function(res){
if (res["status"]) {
actualizarJugadores2(res["bar"]["style"]);
}
}
});
}
function actualizarJugadores2(num) {
var digitos = ("" + num).split("");
var elem = $(".goal").children("dd");
elem.empty();
for (index = 0; index < digitos.length; index++){
elem.append("<span>" + digitos[index] + "</span>")
}
var color = "#F1A90F";
if (num==0) {
color = "#d9534f"
}
elem.children("span").css("background-color",color);
}
Anyone can help me?
Thanks in advance.
Your question is tagged as PHP, so I guess that's an alternative? Simply parse the webpage with PHP Simple HTML DOM Parser. In the example beneath I use the style attribute to find the correct paragraph.
Code:
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://tienda.insidecraft.com/');
foreach($html->find('p[style="text-align:center; font-size:14px;"]') as $item) {
$result = trim($item->plaintext);
}
$progress = explode( ' ', $result)[0];
echo $progress;
?>
Output:
72%

Javascript cannot process JSON text file

I am following some tutorial to pass a JSON text file from server to display the data after some javascript processing on a html file. As a test, try to display a LI of one column, but cannot get any output in the browser. Your help is appreciated.
I tried two approaches.
Approach 1 xmlhttp:
Apparently, the browser complain about the html format:
Uncaught SyntaxError: Unexpected string (15:08:42:080 | error, javascript)
at testJSON3.html:12
Is my xmlhttp call format correct?
Thank you for your help in advance.
Here's JSON text myTutorial.txt:
[
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name 1",
"eventDesc":"2015 class of course name 1"
},
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name21",
"eventDesc":"2015 class of course name "
}
]
And processed by the below html to process the xmlhttp access to the file on server localhost directory phpTWLLT
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost/phpTWLLT/myTutorial.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<li'> + arr[i].courseCode +'</li><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Approach 2 getJSON():
This one is interesting. If the server side is static array ($DEBUG = true:), javascript is able to process and get browser display. But fail when generate the text from mysql ($DEBUG = false).
I am scratching my head to get the $DEBUG=false work? Apparently, both cases generated a valid JSON text.
If $DEBUG is set true,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr#example.com"},{"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"john_doe#example.com"}]
the list displayed in browser.
0
1
If $DEBUG is set false,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"1"},{"active":"1"}]
The browser display is blank.
html file:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<!--
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'> </script>
-->
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script type='text/javascript'>
$(document).ready(function () {
/* call the php that has the php array which is json_encoded */
//$.getJSON('json_encoded_array.php', function(data) {
$.getJSON('json_encoded_array.php', function (data) {
/* data will hold the php array as a javascript object */
$.each(data, function (key, val) {
$('ul').append('<li id="' + key + '">' + val.active + '</li>');
});
});
});
</script>
</body>
</html>
PHP script: json_encoded_array.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/* set out document type to text/javascript instead of text/html */
$DEBUG = true;
if ($DEBUG) {
header("Content-type: text/javascript");
$arr = array(
array(
"active" => "0",
"first_name" => "Darian",
"last_name" => "Brown",
"age" => "28",
"email" => "darianbr#example.com"
),
array(
"active" => "1",
"first_name" => "John",
"last_name" => "Doe",
"age" => "47",
"email" => "john_doe#example.com"
)
);
} else {
require_once('connection.php');
// $m_id= 8 has many enrolled course and 11 got exactly one course enrolled.
$m_id = 8;
$p_id = 1;
$qry1 = "SELECT distinct event.active as active, subject.code as 'courseCode', subject.name as 'courseName', event.event_desc as 'eventDesc' FROM applicant, event, subject, part where applicant.applicant_id = $m_id and applicant.event_id = event.id and event.subject_id=subject.id and part.id = subject.owner_id and part.id = $p_id order by event.active DESC, event.from_month DESC ";
mysqli_set_charset($bd, 'utf-8');
$result = mysqli_query($bd, $qry1);
$arr = array();
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ( $rs = mysqli_fetch_assoc($result) ) {
$colhead = "active";
$str = $rs['active'];
$arr[$i] = array($colhead => $str);
$i++;
// just generate two record for testing
if ($i === 2)
break;
}
}
}
echo json_encode($arr);
?>
For approach 2, did you try debugging the javascript code to check if the data variable contains the expected data?
You could also check the network tab to see if the response data sent from your server is correct.

How do I fetch PHP script output from Javascript?

This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/

How can I get javascript to read from a .json file?

My script currently looks like this:
<script type="text/javascript">
function updateMe(){
var x = 0;
var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
var activity=JSON.parse(jsonstr);
while(x<10){
date = document.getElementById("date"+x).innerHTML = activity.date;
event = document.getElementById("event"+x).innerHTML = activity.event;
x++;
}
}
</script>
Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.
The local .json file looks like this:
{"date":"July 4th", "event":"Independence Day"}
Any suggestions?
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA
If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<p>Take a look at json_demo.txt</p>
</body>
</html>
It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Here's a summary:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Here's the example used:
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.
If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/
Since it isn't working, I'd try using XMLHttpRequests
You could also try AJAX requests:
$.ajax({
'async': false,
'global': false,
'url': "/jsonfile.json",
'dataType': "json",
'success': function (data) {
// do stuff with data
}
});
Documentation: http://api.jquery.com/jquery.ajax/
You can do it like...
Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.
$.ajax({
url: "File.json", //the path of the file is replaced by File.json
dataType: "json",
success: function (response) {
console.log(response); //it will return the json array
}
});
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal;
E.g.
window.portalData = [
{
"kpi" : "NDAR",
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
},
{
"kpi" : "NTI",
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
},
{
"kpi" : "BS",
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
},
{
"kpi" : "SISS",
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
},
{
"kpi" : "MID",
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
}
];
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');

Populating A Page with XML and Javascript/Jquery, checking if the url is the same as an xml tag

I need to create a javascript function that will write a page based on the url, so basically I am trying to create a javascript function that will check the url, and find the corresponding xml item from there.
The reason behind this is so that the html page can just be duplicated, renamed, and the xml updated, and the page will fill in everything else from the xml sheet.
please let me know whether this is the completely incorrect way to do it, of it there is a better way. thanks!!!
XML CODE::
<!--XML INFORMATION-->
<channel>
<design>
<motion><!--design content-->
<item><!--//////////POST//////////POST//////////POST//////////-->
<tag>/portfolio_dec.html</tag>
<!--RSS INFORMATION-->
<title>Decoze</title>
<link>http://payamrajabi.com/portfoliotest.html</link>
<description><img src="http://payamrajabi.com/thumbs/small_jump.png" title="JUMP!." /></description>
<!--PROJECT CONTENT-->
<project><!--project start-->
<titl>TITLE</titl><!--project title-->
<dsc>PROJECT DESCRIPTION</dsc><!--project description-->
</project><!--project end-->
</item><!--//////////END//////////END//////////END//////////-->
</motion>
</design>
</channel>
JAVASCRIPT:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "code/content9.xml",
dataType: "xml",
success: function(xml) {
var xpathname = window.location.pathname;
var xproject = $(xml).find('tag').text();
if (xpathname == xproject) {
$(xml).find('item').children('tag').text(xpathname).each(function(){
var ttl = $(this).find('titl').text();
$('<p>'+ttl+'</p>').appendTo('h1#ttl');
});
$(xml).find('item').children('tag').text(xpathname).each(function(){
var dsc = $(this).find('dsc').text();
$('<p>'+dsc+'</p>').appendTo('h1#ttl');
});
} else {
PUT ERROR MESSAGE HERE
}
}
});
});
and THE HTML:
<html>
<head>
<script type="text/javascript" src="code/jquery-1.3.1.js"></script>
<script type="text/javascript" src="code/project/project_design.js"></script>
</head>
<body>
<h1 id="ttl"></h1>
<p id="dsc"></p>
</body>
</html>
any help would really be appreciated, i am frairly new to javascript/jquery/xml, and am really having trouble with this. The primary thing I want to do is have an xml file that populates a site, with each item being the content for a new page, in this case of a portfolio item.
cheers!
willem
Hmm... I'm afraid you don't quite understand how jquery works.
Your code should look something like this:
var xpathname = window.location.pathname;
var xitem = $(xml).find('tag:contains(' + xpathname + ')').parent();
if (xproject.length != 0) {
$('#ttl').append('<p>' + xitem.find('titl').text() + '</p>');
$('#dsc').append('<p>' + xitem.find('dsc').text() + '</p>');
}
else {
$('#err').text('The page you requested does not exist');
}
Demo 1
Here's a quick demo. Take a look at the source to see the XML and the JavaScript.
http://jsbin.com/ujiho#itemOne
http://jsbin.com/ujiho#itemTwo
http://jsbin.com/ujiho#itemThree
Demo 2
I've created another demo that uses $.get to retrieve the XML from a separate URL.
http://jsbin.com/aqefo#nov
http://jsbin.com/aqefo#dec
The XML: http://jsbin.com/afiwa
Here's the JavaScript. Let me know if you need help understanding anything.
$(function(){
$.get(
'http://jsbin.com/afiwa',
function(xml){
var hash = window.location.hash.substring(1);
if ($.trim(hash) === '') {
showError();
return;
}
var xitem = $(xml).find('urlname:contains(' + hash + ')').parent();
if (xitem.length != 0) {
$('#ttl').append(xitem.find('titl').text());
$('#dsc').append( xitem.find('dsc').text());
}
else {
showError();
}
function showError() {
$('#err').text('The page you requested does not exist');
}
}
);
});

Categories