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.
Related
I have red a lot of posts about how to add data to json file and I tried to put it all together and use for my situation, but it's not working. Basically what I do is get data from html file with javascript, then use XMLHttp request to send that data to php file and from php file I am trying to add the data to .json file. Anywho, it is not adding it and I don't know why and where is the problem.
My question is about the XMLHttp request. Is it correct? Why not?
And about php file. If the problem is in XMLHttp request, would the php file add the data to .json file? I am just trying to get anything in the json file, so i could start thinking about algorithms for making it viable. XMLHttp request is pretty new thing for me. For understanding, here is my code:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/style_mob.css" type="text/css" rel="stylesheet">
<script src="script/jquery.js"></script>
<script src="script/sendData.js"></script>
</head>
<body>
<div id="top">
<h1>Click only in case of an emergency!</h1>
</div>
<div id="divButtons">
<button class="button" id="polizei">Polizei</button>
<button class="button" id="feuerwehr">Feuerwehr</button>
<button class="button" id="krankenwagen">Krankenwagen</button>
</div>
</body>
</html>
sendData.js:
$( document ).ready(function() {
var type;
var latitude;
var longitude;
var currentdate = new Date();
$(".button").click(function(){
type = $(this).attr("id");
var dateTime = "Date: " + currentdate.getDay() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " time - "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(sendData);
} else {
alert("Geolocation is not supported by this browser.");
}
function sendData(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
var hr = new XMLHttpRequest();
hr.open("POST", "emergencyData.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert("about to send data to php file");
hr.send("type="+type+"&latitude="+latitude+"&longitude="+longitude+"$dateTime="+currentdate+"");
});
});
emergencyData.php:
<?php
header("Content-Type: application/json");
$type = $_POST["type"];
$latit = $_POST["latitude"];
$longit = $_POST["longitude"];
$dateTime = $_POST["dateTime"];
echo $type;
// Loading existing data:
$json = file_get_contents("emergencyData.json");
$data = json_decode($json, true);
// Adding new data:
$data[0] = array('type' => $type, 'latitude' => $latit, 'longitude' => $longit, 'date' => $dateTime);
// Writing modified data:
file_put_contents('emergencyData.json', json_encode($data, JSON_FORCE_OBJECT));
?>
You have a typo in javascript.
hr.send("type="+type+"&latitude="+latitude+"&longitude="+longitude+"$dateTime="+currentdate+"");
You have a $ at dateTime which should be &
Also I think you wanted &dateTime="+currentdate+"" to be &dateTime="+dateTime. Extra +"" is unnecessary.
And last thing, if you want to keep adding new data instead of overwriting old data, in PHP script use:
$data[] = array('type' => $type, 'latitude' => $latit, 'longitude' => $longit, 'date' => $dateTime);
Otherwise everytime the old JSON data will get replaced by new one.
Current setting:
In the same PHP document I have a PHP randomizer function and the HTML that calls that function -- a separate txt document with strings that are called by the php function:
Function
<?php
function rand_line($fileName, $maxLineLength = 4096) {
$handle = #fopen($fileName, "strings.txt");
if ($handle) {
$random_line = null;
$line = null;
$count = 0;
while (($line = fgets($handle, $maxLineLength)) !== false) {
$count++;
if(rand() % $count == 0) {
$random_line = $line;
}
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
fclose($handle);
return null;
} else {
fclose($handle);
}
return $random_line;
}
}
?>
I call the function in the HTML using:
<?php echo rand_line("strings.txt");?>
<input type="button" value="Another String" onClick="window.location.reload()">
This tends to be slow when multiple users access the page and press the button to obtain a new status.
What I would like to achieve:
Improve the performance and make the whole thing not so heavy: maybe the randomizer is unnecessarily complicated and I could work with AJAX calls for example, but if possible keeping the string list inside the strings.txt file and separated from the PHP script and HTML.
Sorry if I don't know what I'm talking about... I'm not a proficient programmer. Just a guy that hacks stuff together once in a while :)
You really don't want to use window.location.reload();
That is terrible... You do not want to refresh a page...
location.reload() sends http request for a whole new page (whole HTML), and then not only that your browser needs to render whole HTML again, you have to transfer more duplicated data through a network, from point A to point B.
You should send HTTP request only for a data that you need (you don't need whole HTML again, you loaded it the 1st time you visited page).
Instead, use XMLHttpRequest javascript library (AJAX) to request only for a portion of data (in your case => random line string)
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<script type="text/javascript">
function loadDoc(url, cfunc) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
};
xhttp.open("GET", url, true)
xhttp.send();
}
function randomLine(xhttp) {
alert(xhttp.responseText);
}
</script>
</head>
<body>
<input type="button" value="Get random line" onClick="loadDoc('http://localhost:8080/myScript.php', randomLine)">
</body>
</html>
PHP:
myScript.php
<?php
function rand_line($fileName, $maxLineLength = 4096)
{
...
}
echo rand_line("strings.txt");
?>
*EDIT #2*
Fully-functioning script. Grabs initial strings via PHP, and stores in array for later JavaScript usage. Minimizes # of calls.
PHP to grab strings from file; generates a default (random) string, as well as an array of strings for later use with button.
/**
* #input array $file
* #return array (mixed) [0] => string, [1] => array
*/
$randomStringFromFile = function($file) {
if (!$file) return false;
/**
* #return Removes carriage returns from the file
* and wraps $val with single-quotes so as
* to not break JavaScript
*/
$add_quotes = function(&$val) {
return str_replace("\n", "", "'$val'");
};
return [$file[rand(0, count($file)-1)], array_map($add_quotes, $file)];
};
$randomString = $randomStringFromFile( #file('strings.txt') ) ?: false;
JavaScript
<div id="string_container"><?php echo $randomString[0]; // defaults random string to page ?></div><br>
<button onclick="getString();">Another String</button>
<script>
var getString = function() {
var arr = [<?php echo implode(',', $randomString[1]); ?>],
setString = document.getElementById('string_container').innerHTML = arr[Math.floor(Math.random() * arr.length)];
};
</script>
Place the above in your page and you should be good to go.
EDIT (ORIGINAL)
We can remove PHP from the equation entirely using the following (fastest method):
<div id="string_container"></div><br>
<button onclick="getString();">Another String</button>
<script>
var getString = function() {
var request = new XMLHttpRequest(),
file = 'strings.txt';
request.open('GET', file);
request.onload = function() {
if (request.status === 200) {
var arr = request.responseText.split("\n"), /** assuming line breaks in file are standard carriage returns (Unix); "\r" if Windows */
setString = document.getElementById('string_container').innerHTML = arr[Math.floor(Math.random() * arr.length-1)];
}
};
request.send();
};
</script>
ORIGINAL w/PHP
We can simplify the PHP even further, removing loops from the equation altogether.
$randomStringFromFile = function($file) {
if (!$file) return false;
return $file[rand(0, count($file)-1)];
};
echo $randomStringFromFile( #file('strings.txt') ) ?: 'No worky!';
Using file() will return the contents in an array, thus allowing you to simply select a key at random and return the value.
NOTE On average, $file[rand(0, count($file)-1)] outperformed array_rand() (E.g. $file[array_rand($file)];) when selecting a key at random. By negligible amounts, have you.. ~0.0002s vs ~0.0005s, respectively.
You can simplify your code
function rand_line($fileName, $maxLineLength = 4096) {
$f = file($fileName);
$length = $maxLineLength + 1;
do {
$line = $f[array_rand($f)];
$length = strlen($line);
} while ($length > $maxLineLength);
return $line;
}
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".
I need the onkeyup to fire more than once, but it seems to be only firing once!
When I enter something into the input box, it searches, but then whenever I backspace and search something else, the div stay's the same..
Here is my code:
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'dam_search.php?dam_text=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
Here is dam_search.php
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
ALSO: I am wondering how I can put the return of the name's it has searched into a dropdown from the input box instead of into the div, so when I click on one of the names, it auto fills the input box.
Thank you!
Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.
The code requires that you download the AjaxRequest library I mentioned in an earlier comment.
(http://ajaxtoolbox.com/request/)
Here, I demo a few principles.
Arranging the data into a php class
constructing an array of instances of this class
returning this array as JSON
catching the JSON text and turning it back into an object in JS
Processing the data
I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.
The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!
Hope it's useful for you. Any questions, just ask. :)
1. jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
if (!isset($_GET['wildcard']))
$wildCard = "*.*";
else
$wildCard = $_GET['wildcard'];
foreach (glob($wildCard) as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. readDir.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/ajaxRequestCompressed.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function myGetAjaxResponseWithCallback(url, target, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target); }
}
);
}
function getResults1()
{
var url = "jsonDir.php";
var target = byId('resultsDiv');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}
function getResults2()
{
var url = "jsonDir.php?wildcard=*.png";
var target = byId('resultsDiv2');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}
function jsonDataReceived1(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mStr = "There were " + resultObject.length + " records returned" + "<br>";
var mSel = newEl("select");
mSel.addEventListener('change', doAutofill, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = mStr;
targetContainer.appendChild(mSel);
}
function jsonDataReceived2(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mSel = newEl("select");
mSel.addEventListener('change', showSelectedImg, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(mSel);
}
function doAutofill(e)
{
var curSelIndex = this.value;
var curText = this.options[curSelIndex].label;
byId('autofillMe').value = curText;
}
function showSelectedImg(e)
{
byId('previewImg').src = this.options[this.value].label;
}
</script>
<style>
img
{
border: solid 2px #333;
}
</style>
</head>
<body>
<button onclick='getResults1()'>Get *.* dir listing</button> <input id='autofillMe'/>
<div id='resultsDiv'></div>
<hr>
<button onclick='getResults2()'>Get *.png dir listing</button> <img id='previewImg' width='100' height='100'/>
<div id='resultsDiv2'></div>
</body>
</html>
Found out my problem. The query wasn't correctly being processed!
I had the variable $dam_text as the LIKE statement, when it should have been $dam:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
getSuggest($text);
}
function getSuggest($text) {
$dam = $_GET['dam_text'];
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!
OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();
To make sure your browser is working correctly try this
<script type="text/javascript">
function suggest1() {
document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
You should see the div change for every keystroke that occurs in the input.
There is two many unknowns for me to directly point at your actual issue.
Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup
T test to onkeyup on your system/browser:
Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).
Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/
Swapping out your PHP for the echo service works fine (with a bit of a typing delay)
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
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.