jquery ui autocomplete special characters - javascript

I created a small jquery example with jquery UI autocomplete
$(function() {
//autocomplete
$(".selector").autocomplete({
source: "getdata.php",
minLength: 1
});
})
getdata.php:
<?php
if (isset($_GET['term'])){
$return_arr = array();
try {
$connectionInfo = array('Database'=>'db','UID'=>'sa','PWD'=>'pw');
$connection = sqlsrv_connect('db-server',$connectionInfo);
if($connection)
{
$result = sqlsrv_query( $connection, 'SELECT TOP 10 test FROM table WHERE test like ? ',array('%'.$_GET['term'].'%'));
while($row = sqlsrv_fetch_array($result)){
$row = array_map('utf8_encode', $row);
$return_arr[] = $row['test'];
}
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
and it works but the problem is that the data source is not Unicode so the strings don't show up correctly I don't know what kind of transformation to use.
If possible I would like to keep the same encoding as in database (Windows-1250) as this project might also insert stuff back from the website to the db
I tried just to dump the original strings but then I get values with special characters as null in json when the return array get's transformed

You can encoder your data before display it in autocomplete

Related

Handling special characters in and out of mysql

I'm building a leaflet web app which stores messages assigned to geolocations.
I add data one line at a time by sending it from javascript to PHP using:
$name = mysqli_real_escape_string($conn, $_POST['NAME']);
$latitude = mysqli_real_escape_string($conn, $_POST['LATITUDE']);
$longitude = mysqli_real_escape_string($conn, $_POST['LONGITUDE']);
$message = mysqli_real_escape_string($conn, $_POST['MESSAGE']);
$sql = "INSERT INTO geoData (NAME,LATITUDE,LONGITUDE,MESSAGE)
VALUES ('$name', '$latitude', '$longitude', '$message')";
I get the data back out using PHP to echo the data back to javascript using:
$conn = mysqli_connect($dbServername,$dbUsername, $dbPassword, $dbName);
if(! $conn ){
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT * FROM geoData';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
} else {
echo "0 results";
}
mysqli_close($conn);
<script type="text/javascript">
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
</script>
This works fine UNLESS the message has special characters such as apostrophes for example 'Dave's dogs's bone'. This creates an error
What is the best practise for such an application which uses PHP and javascript. I think I need some way to encode the special characters which javascript can then decode and display.
The error comes as:
Uncaught SyntaxError: missing ) after argument list
<script type="text/javascript">
var data = JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGITUDE":"-1.3100980520","MESSAGE","Dave's Dog's Bone"}] ' );
</script>
Many thanks
The issue is your JSON.parse() which isn't needed at all in this case.
Change:
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
to
var data = <?= json_encode($rows); ?>;
JSON.parse() is for parsing stringified json. Echoing the result from json_encode() will give you the correct result straight away.
Side note
I would recommend adding $rows = []; before your if (mysqli_num_rows($result) > 0) or json_encode($rows) will throw an "undefined variable" if the query doesn't return any results (since that variable currently is created inside the loop when you're looping through the results).
Side note 2
When making database queries, it's recommended to use parameterized Prepared Statements instead of using mysqli_real_escape_string() for manually escaping and building your queries. Prepared statements are currently the recommended way to protect yourself against SQL injections and makes sure you don't forget or miss to escape some value.
You produce that error yourself by adding ' in json. If you want check that use this:
JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGDITUTE":"-1.3100980520","type":"bad","reason":"Dave\'s Dog\'s Bone","improvement":"","reviewed":"0"}] ' );
And if you want correct that in main code use str.replace(/'/g, '"') for your var data, before parse it to json.

i have code like this for auto complete feature but am not able fetch the data from the data base.kindly help me out

My aim is to fetch location from the database once user start entering in the input tetc field
i have done all the coding properly but the also am not able to fetch the data from the database.
<!--My java script code-->
$(function() {
$( "#LocationName" ).autocomplete({
source: 'search.php'
});
});
<!--My Search.php code-->
<?php
include('dbConnect.php');
$searchTerm = $_GET['term'];
$sql = mysql_query ("SELECT LocationName,From arealistmain WHERE LocationName LIKE ?");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'value' => $row['LocationName'].'',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
?>
First of all don't use mysql_* functions as they were deprecated in PHP 5.5 and removed in PHP 7 instead use mysqli_* functions.
Second thing you should always sanitize user input don't just do $searchTerm = $_GET['term']; read more about this
Then your SQL query should read
$query = "SELECT LocationName From arealistmain WHERE LocationName LIKE '%$searchTerm%';";
The comma before FROM removed and the $searchTerm is enclosed in two percentage signs to match all
Update your query to below code
$sql = mysql_query ("SELECT LocationName From arealistmain WHERE LocationName LIKE '%".$searchTerm."%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = $row['LocationName'];
}

Typeahead: Return JSON array with multiple data

I'm using bootstrap's typeahead and I'm wondering how I can return a JSON array with multiple pieces of data for each result.
For example, I want to be able to return two pieces of data for each result, the name and the description. How would this be done?
The only way to do this is using "Multiple Datasets" as mentioned in the following link:
http://twitter.github.io/typeahead.js/examples/#multiple-datasets
You'll have to create 2 different sources: one for the "name" and one for the "description".
In case you don't want to search using the "description", then you can use the following code:
http://twitter.github.io/typeahead.js/examples/#custom-templates
You'll be able to search using the "name" and the description will be displayed next to the name.
This code will make the output to show result from two columns when you type. You have to change only in search.php code, not any other place. Try it and give feedback.
$key=$_GET['key'];
$mysqli = new mysqli("localhost", "root", "", "yourbd");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$result = $mysqli->query("select * from yourtb where yourcolumn LIKE '%{$key}%'");
if (!$result) {
die(mysqli_error($mysqli));
}
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r['col1']. ' - ' . $r['col2'];
}
echo json_encode($rows);

consult with typeahead.js database

Would like to query the database with typeahead.js v.0.10.2 .
I tried ,but I failed, I've bundled with the plugin.
JS:
$(document).ready(function() {
$('input.typeahead').typeahead({
name: 'user-search',
remote: 'data.php' // you can change anything but %QUERY
minLength: 1, // send AJAX request only after user type in at least 3 characters
limit: 10 // limit to show only 10 results
});
});
PHP:
$dato = $_POST['query'];
require("connect.inc.php");//database
$query = mysql_query("SELECT artist FROM music WHERE artist REGEXP '^$dato'");
$array = array();
while($fila = mysql_fetch_array($query)) {
$array = $fila['artist'];
}
return json_encode($array);
instead of return json_encode($array); use echo return json_encode($array);

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories