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.
Related
I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>
I'm having an issue appending data from loop. I am trying to append the result that is clicked on, but when theres multiple results every result is appended on click. I am using ajax to retrieve search results. Below is my php section. I think the issue is that every result has the same class so it appends every one, but I can't figure out how to identify only one
if(isset($_POST['inviteSearch'])) {
include_once "connect.php";
$con = getConnection();
$search = "%{$_POST['inviteSearch']}%";
$query = "SELECT FirstName,LastName FROM `Profiles` WHERE FirstName LIKE ? OR LastName LIKE ? ";
$stmt = $con->prepare($query);
$stmt->bind_param("ss", $search ,$search);
if(!($stmt->execute())) {
die(mysql_error());
} else {
$result = $stmt->get_result();
$output = '<ol>';
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['FirstName'] . " " . $row['LastName'];
$output .= "
<li id='invitetoken'>
<p>$name</p>
</li>
<script>
$(document).ready(function(){
$('#invitetoken').click(function(){
$('.invitedSection').show();
$('.invitedList').append('<li><p>$name</p><button>×</button></li>');
});
});
</script>
";
}
} else {
$output .= "<h3>We could not find $search</h3>";
}
$output .= '</ol>';
echo "$output";
}
}
To start with the obvious, please use parameterized queries you are currently vulnerable to SQL injection attacks.
You are appending the same js repeatedly in your while loop, that is generally bad practice. I'm going to break this up a bit, since you have both php and JS issues
PHP
Here just generally cleaning up and using parameterized queries and class based mysqli (in line with the above suggestion comments). I also moved the javascript out of the loop as repeating it over and over doesn't achieve anything. Obviously haven't tested my changes but they are fairly boilerplate (see the docs)
if (!isset($_POST[''inviteSearch']) {
return;
}
$connection = new mysqli('host', 'user', 'password', 'schema');
$param = filter_input(INPUT_POST, 'inviteSearch', FILTER_SANITIZE_STRING);
// setup query
$query = "SELECT CONCAT(FirstName, ' ', LastName) AS name
FROM Profiles
WHERE (FirstName LIKE ? OR LastName LIKE ?)";
// prepare statement
$stmt = $connection->prepare($query);
// need variable bind for each tokenized parameter
$stmt->bind_param('ss', $param, $param);
$stmt->execute();
$results = $stmt->get_result();
$output = makeOutput($results);
// Siloing your presentational elements for clarity.
function makeOutput($results) {
if ($results->num_rows === 0) {
return "<h3>We could not find $search</h3>";
}
$output = '<ol>';
while ($row = $results->fetch_assoc()) {
$output .= "<li class='invitetoken'><p>{$row['name']}</p></li>";
}
$output .= '</ol>';
return $output;
}
JavaScript
A few things here, enclosed the function into an IIFE to keep it namespace contained, generally a good practice. The changes to the click handler let the callback handle the update dynamically for any matching class that is clicked. I reference this (in this case it is helpful to think of this as event.target) and use it to find the name to be appended. from there it is pretty similar to what you already had. Of note, I'm using let for variable definitions and template literal syntax for the string data, but you should look up their availability and decide whether you need to worry about old browser support :).
(function($) {
$(document).ready(function(){
$('.invitetoken').on('click', function() {
let name = $(this).children('p').text()
, string = `<li><p>${name}</p><button>×</button></li>`;
$('.invitedSection').show();
$('.invitedList').append(string);
});
});
})(jQuery);
I have seen some answers similar to this but they wont work for me.
I want to select data from a mysql database using mysqli / PHP and then pass the results to javascript.
I have the $conn stuff just above this, my code is at the very top of the file above the html, my script tags are in the body of the html. Is the correct place to have them? This just returns undefined, and if i try tweaking it i get unexpected < in index where i try and save it to the var ar. Or i can get unexpected ';' at the same line. Code shown below return unexpected ';'.
PHP
$query = "SELECT * FROM table";
$result = $conn->query($query);
while($row = $result->fetch_array())
{
$rows[] = $row;
}
$conn->close();
JavaScript
<script type="text/javascript">
var ar = <?php echo json_encode($rows)?>;
console.log(ar[0][0]);
</script>
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.
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