I have a Server file written in php, and a client html file (mainly javascript), I want to have both put into one file and still communicate. I tried copying the php code of the server above the client code but it didn't work. So this is how it was like:
<!doctype html>
<html>
<meta charset='UTF-8' />
<style>
input, textarea {border:1px solid #CCC;margin:0px;padding:0px}
#body {max-width:800px;margin:auto}
#log {width:100%;height:400px}
#message {width:100%;line-height:20px}
</style>
<?php
// prevent the server from timing out
set_time_limit(0);
// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';
// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
// check if message length is 0
if ($messageLength == 0) {
$Server->wsClose($clientID);
return;
}
$x = 0;
//The speaker is the only person in the room. Don't let them feel lonely.
for ($i=1; $i <= 10; $i++) {
$q=".68.111.160";
$string =100+$i*10;
$string .= $q;
$Server->wsSend($clientID, $string);
sleep (3);
}
}
// when a client connects
function wsOnOpen($clientID)
{
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
$Server->log( "$ip ($clientID) has connected." );
//Send a join notice to everyone but the person who joined
foreach ( $Server->wsClients as $id => $client )
if ( $id != $clientID )
$Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}
// when a client closes or lost connection
function wsOnClose($clientID, $status) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
$Server->log( "$ip ($clientID) has disconnected." );
//Send a user left notice to everyone in the room
foreach ( $Server->wsClients as $id => $client )
$Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}
// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('127.0.0.1', 9300);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="fancywebsocket.js"></script>
<script>
var Server;
function log( text ) {
$log = $('#log');
//Add text to log
$log.append(($log.val()?"\n":'')+text);
//Autoscroll
$log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
}
function send( text ) {
Server.send( 'message', text );
}
</script>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://datamaps.github.io/scripts/datamaps.world.min.js?v=1"></script>
<script src="converter.js"></script>
<div id="container1" style="position: relative; width:900px; height: 700px;"></div>
<script>
var map = new Datamap({
scope: 'world',
element: document.getElementById('container1'),
projection: 'mercator',
fills: {
lt50: 'rgba(0,244,244,0.9)',
on: 'red',
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(50,0,0)',
off: "#ABDDA4",
defaultFill: "#ABDDA4"
},
data: {
}
})
var x;
var colors = d3.scale.category10();
$(document).ready(function() {
log('Connecting...');
Server = new FancyWebSocket('ws://127.0.0.1:9300');
$('#message').keypress(function(e) {
if ( e.keyCode == 13 && this.value ) {
log( 'You: ' + this.value );
send( this.value );
$(this).val('');
}
});
//Let the user know we're connected
Server.bind('open', function() {
log( "Connected." );
});
//OH NOES! Disconnection occurred.
Server.bind('close', function( data ) {
log( "Disconnected." );
});
//Log any messages sent from server
Server.bind('message', function( payload ) {
log( payload );
var ip = payload;
$.get("http://ipinfo.io/" + ip, function(response) {
x = response.country;
}, "jsonp");
var interval_x = window.setInterval(function() {
var country_name = convert[x];
var interval_1 = window.setInterval(function() {
var country = {}
var country = {}
country[country_name] = {
fillKey: 'on'
}
map.updateChoropleth(country);
}, 2000);
myVar = window.setTimeout(function() {
clearInterval(interval_1);
var country = {}
country[country_name] = {
fillKey: 'off'
}
map.updateChoropleth(country);
}, 4000);
}, 4000);
});
Server.connect();
});
//---------------------------------------IP Goes Here------------------------------------------------
</script>
<body>
<div id='body'>
<textarea id='log' name='log' readonly='readonly'></textarea><br/>
<input type='text' id='message' name='message' />
</div>
</body>
</html>
But it wouldn't work, knowing that this was put in an html file.
We don't have all your embedded scripts for this special case. But generally you can put HTML, CSS, PHP and JavaScript in the same file. The file has to end with '.php' and PHP must be installed ("test.php"):
<!doctype html>
<html><head>
<title>Test</title>
</head><body>
<div id="test">
<?php echo 'foobar'; ?>
</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
</body></html>
Should output "foobar".
Related
I have the following code:
- the javascript helps me select a text file and it chooses only the id from the text file. example of text file is below:
ID,Name,Surname
re-002,ram,kelu
rf-897,rem,juke
When i added the button 'loader', the javascript readText no longer displays the id that it took from the text file.
What i want to do is to allow user to select a text file, read only the ids, and then place the ids in my database.
My html page:
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "-":
output = output.split("\n").filter((line, i) => i != 0).map(line => line.split(",")[0]).join("<br/>\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}
}
$("#loader").on("click", function(){
var upload = $.ajax({
type: "POST",
url: "loader.php",
data: {array:output},
cache: false,
beforeSend: function() {
}
});
</script>
</head>
<body>
<h1> Utilisateur Nommé </h1>
<h3> Import : <button id="loader" onclick='btn()'> Import</button>
<h3> Choose file : <input type="file" onchange='readText(this)' />
</h3>
</body>
</html>
My php page 'loader.php':
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_NAME', 'dbapp' );
$array = json_decode($_POST['output']);
$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME');
$arr_id = $mysqli->real_escape_string($array[0]);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO `user` (id) VALUES($arr_id)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br
/>';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
// close connection
$mysqli->close();
?>
Your code is brittle. But moving output declaration outside readText might help actually send some data
var output; // move the output declaration here
var reader = new FileReader();
function readText(that) {
if (that.files && that.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
output = e.target.result;
//process text to show only lines with "-":
output = output.split("\n").filter((line, i) => i != 0).map(line => line.split(",")[0]).join("<br/>\n");
document.getElementById('main').innerHTML = output;
}; //end onload()
reader.readAsText(that.files[0]);
}
}
function btn() {
var upload = new XMLHttpRequest();
upload.open("POST", "loader.php");
upload.send(JSON.stringify({ array: output }))
upload.onreadystatechange = function () {
if (upload.readyState === XMLHttpRequest.DONE) {
if (upload.status === 200) {
alert(upload.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
}
<main id="main"></main>
<h1> Utilisateur Nommé </h1>
<h3> Import : <button id="loader" onclick="btn()"> Import</button>
<h3> Choose file : <input type="file" onchange='readText(this)' />
Bonus: done without jQuery.
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
Problem:
When I start up any Browser, it opens up with its default web page, I open a session to my
Test File Upload with Progress bar Web Application in that Tab, or that same Web App. in a new Tab. When I
start the first file upload, it shows the Progress bar to go straight to 100% even though the file is still
uploading. If I then do the file upload again, it works as expected, the progress bar shows the file being
loaded, eg 20%, 43%, 80%, 98% then Done.
I am using the example that is published at:-
https://www.sitepoint.com/tracking-upload-progress-with-php-and-javascript/
I have modified it slightly in an effort to find out what is going on.
This problem occurs on my Web Site which is on the Internet and on my Local Server.
Both systems are LINUX, using Apache2. The Web Site on the Internet is using PHP 5.6.30. My local server
is using PHP 7.1.5.
This same problem can be reproduced when using a Cellphone running Safari, Chrome, or FireFox.
So this looks like a Server based issue or some coding issue I have either at the Client
or Server end.
I use this type of code to upload Video files and my work around is to assume that the file
will not be fully uploaded until at least after the first progress percent loaded calculation. If I
get the '100' reply on the first pass I assume that the progress bar reading is wrong and suggest
the the file upload should be tried again. The second upload always works. In my case the maximum
size allowed for the video file 28MB.
Can anybody assist with this problem?
Below is a copy of my two PHP Web Pages.
File: progress.php
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
{
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
} else
{
echo "100";
}
?>
File: upload2.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
// move_uploaded_file()
$folder = "tmp/";
//upload the file
move_uploaded_file($_FILES["userfile"["tmp_name"], "$folder" . $_FILES["userfile"]["name"]);
}
?>
<html>
<head>
<title>File Upload Progress Bar</title>
<style>
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="Message"></div>
<form action="" method="POST"
id="form_60" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="form_60"
name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
<!script type="text/javascript" src="upload2.js"></script>
<script type="text/javascript">
var FirstTime = 'Y';
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php", false); // was GET
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("Message").innerHTML = response + "%";
alert(response);
if (response < 100) {
FirstTime = 'N'
setTimeout("sendRequest()", 1000);
}
else {
alert(response);
toggleBarVisibility();
if (FirstTime == 'N')
{
document.getElementById("Message").innerHTML = "Done.";
}
if (FirstTime == 'Y')
{
document.getElementById("Message").innerHTML = "Error.";
alert('System error, please try again.')
}
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("form_60").onsubmit = startUpload;
})();
</script>
</body>
</html>
I have now found a workaround, which is listed below. It involves doing a Dummy request from a startup page in my application. In my case I use the Login Web Page to put the Dummy code.
<script type="text/javascript">
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php", false); // was GET
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http)
{
var response;
if (http.readyState == 4)
{
response = http.responseText;
if (response < 100)
{
setTimeout("sendRequest()", 1000);
}
}
}
function startUpload() {
setTimeout("sendRequest()", 1000);
}
window.onload = function() {
startUpload();
}
</script>
Now that I have learnt a bit more about Session Variables it seems that to follow the rules I should have put:-
session_start();
at the start of the upload2.php web page, as this is where the variable information is coming from in the first instance. This then works fine.
It looks as though the session is not reading in the if statement at the beginning. You just echo out 100% if the Session doesn't exist. If you ammend this part:
Progress.php
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
{
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
} else {
$_SESSION[$key]["bytes_processed"] = 0;
}
?>
It shouldn't jump straight to 100% because the Session will be active at this point rather than after the first upload. Not tested but worth a try, I'll stick this code on my test server when I get a chance to do a proper test if you don't beat me to it!
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.
I have these 3 files that I found, its a plugin that loads more data when a user click a button and uses ajax and json to do that. It works very well and has only one problem. It is not displaying the data in screen but only the parenthesis (). The thing is that I don't know so good javascript to solve the problem if it is in js for that I asking your help. If anyone can solve it I would appreciated this.
The source for the plugin is this
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Load more</title>
</head>
<body>
<div class="articles">
<div class="items">
<div class="item">
<h3><span data-field="title"></span> (<span data-field="id"></span>)</h3>
<p data-field="description"></p>
</div>
</div>
Load more
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="loadmore.js"></script>
<script>
$('.articles').loadmore({
source: 'articles.php',
step: 2
});
</script>
</body>
</html>
articles.php
<?php
header('Content-Type: application/json');
include('db_conx.php');
?>
<?php
$articles = array();
$start = isset($_GET['start']) ? (int)$_GET['start'] - 1 : 0;
$count = isset($_GET['count']) ? (int)$_GET['count'] : 1;
$article = mysqli_query($db_conx, "SELECT * FROM articles LIMIT {$start}, {$count}");
$articlesTotal = mysqli_query($db_conx, "SELECT COUNT(*) as count FROM articles");
$articlesTotal = mysqli_fetch_assoc($articlesTotal);
$articlesTotal = $articlesTotal['count'];
if ($articlesCount = $article->num_rows) {
$articles = $article->fetch_all();
}
echo json_encode(array(
'items' => $articles,
'last' => ($start + $count) >= $articlesTotal ? true : false,
'start' => $start,
'count' => $count
));
?>
loadmore.js
(function($) {
"use strict";
$.fn.loadmore = function(options) {
var self = this,
settings = $.extend({
source: '',
step: 2
}, options),
stepped = 1,
item = self.find('.item'),
items = self.find('.items'),
finished = function() {
self.find('.items-load').remove();
},
append = function(value) {
var name, part;
item.remove();
for (name in value) {
if (value.hasOwnProperty(name)) {
part = item.find('*[data-field="'+name+'"]');
if (part.length) {
part.text(value[name]);
}
}
}
item.clone().appendTo(items);
},
load = function(start, count) {
$.ajax({
url: settings.source,
type: 'get',
dataType: 'json',
data: {start: start, count: count},
success: function(data) {
var items = data.items;
if (items.length) {
$(items).each(function(index, value) {
append(value);
});
stepped = stepped + count;
}
if (data.last === true) {
finished();
}
}
});
};
if (settings.source.length) {
self.find('.items-load').on('click', function() {
load(stepped, settings.step);
return false;
});
load(1, settings.step);
} else {
console.log('Source required to load more.');
}
};
}(jQuery))
Database
id int not null auto_increment primary key,
title varchar(200),
description text
Is good to have at least above 10 inserts to see it work right and understand it!
Found the solution.. The problem was at articles.php file in line 19 instead of
if ($articlesCount = $article->num_rows) {
$articles = $article->fetch_all();
}
it must have declare that fetch is assoc so here is the solution:
if ($articlesCount = $article->num_rows) {
$articles = $article->fetch_all(MYSQLI_ASSOC);
}
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.