Securely communicate with mysql server (MariaDB) using javascript and php (NO jQuery) - javascript

I am trying to achieve two things:
(1) Get text from a contenteditable div, use javascript to send that text to php, use php to send that data to a MySQL database and save it
(2) retrieve the saved data/text and reinsert it into a contentedtiable div
All of this whilst NOT using jQuery
What I've got so far:
index.html
<body>
<div contenteditable="true" id="editable"></div>
<button onClick="send_data();">Save text</button>
<button onClick="retrieve_data();">Get text</button>
</body>
javascript.js
function send_data() {
var php_file = "connection.php";
var http_connection = new XMLHttpRequest();
http_connection.open("POST", php_file, true);
http_connection.onreadystatechange = function() {
if(http_connection.readyState == 4 && http_connection.status == 200) {
alert(http_connection.responseText);
}
}
http_connection.send(document.getElementById('editable').innerText);
}
function retrieve_data() {
// I do not know what to put here
}
connection.php
<?php
$servername = "localhost";
$username = "mysql_user";
$password = "secure_password";
$dbname = "some_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
if(!conn) {
echo 'No connection';
}
if(!mysqli_select_db($conn,'some_database')) {
echo "No database";
}
$some_val = $_GET['text']
$sql = "SELECT text FROM some_database";
$result = $conn->query($sql);
echo $result;
$conn->close();
?>
Edit: what my code fails to do is to upload text as well as recieve text.

Some problems in the js:
http_c is not defined
readyState is spelled incorrectly
the send method needs to be outside the onreadystatechange callback
Once those things are corrected, program should give different, which is not to say expected, result.
Other things:
The js is sending a 'POST' request. The php is looking for $_GET["text"] which will give undefined error. I'm speculation this $sql = "SELECT text FROM some_database"; will fail (if it reaches that line) unless there is a table in the database named "some_database".
Suggest, for starters, get the ajax working by short-circuiting the code in connection.php to something like
echo "You are here";
exit;
Then gradually working forward between the js and the php until programs give you what you want.

Related

JavaScript HttpRequest always return the same results

I have a HTML page JavaScript which send a GET request data to PHP file to return all datas saved in the database . PHP replies with a HTML-table - that works fine!
But: When if i click a button (which calls the same JavaScript function) to update my table in order to display the new data, i get the same result (and i have definitely new data on table).
If I call the PHP manually via the browser it'll show me the new results immediately and at this moment it is also working with JavaScript (but only once).
Here is a part of my code.
HTML/JS:
<button onclick="GetData()"></button>
<div id="test"></div>
<script>
function GetData(){
var xhttp = new XMLHttpRequest();
document.getElementById("test").innerHTML = "";
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200){
document.getElementById("test").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../GetData.php", true);
xhttp.send();
}
</script>
PHP:
//DB details
$dbHost = 'localhost';
$dbUsername = 'lalalala';
$dbPassword = 'lalalalal';
$dbName = 'lalalala';
//Create connection and select DB
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName) or die ("UUUUPS");
$sql = "select name, beschreibung, image, video from data";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$return = '<table class ="table table-hover"><thead><tr><th scope="col">Name</th><th scope="col">Beschreibung</th><th scope="col">Bilddatei</th><th scope="col">Video-Url</th></tr></thead><tbody>';
// output data of each row
while($row = $result->fetch_assoc()) {
$return .= "<tr><td>".$row["name"]."</td><td>".$row["beschreibung"]."</td><td><img src=data:image/png;base64,".base64_encode($row["image"])."/></td><td>".$row["video"]."</tr>";
}
$return .= "</tbody></table>";
$db->close();
echo $return;
} else {
echo "0 results";
}
Thank you for your help!
It seems your browser is caching your result, that's why you see data.
You can test it like this:
var random = Math.floor(Math.random() * 100);
xhttp.open("GET", "../GetData.php?"+random, true);
If this helps, look into expire headers in your PHP script. Also, the way you're doing queries in quite outdated. It's a very PHP4 way. Have a look here: http://php.net/manual/en/book.mysqli.php
I guess you probably know this, but just in case. Have you had a look in your browsers inspector, when testing you html page? especially the network tab within that inspector. There you can see the actual response from the server and you can see if it is served from cache or fetched (you can even disable cache there), maybe this helps.
Kind regard,
Mark

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

Sending value of PHP variable to Javascript document

So I am trying to reach into a MySQL table and draw out a value. I have the following PHP that does so:
<!DOCTYPE html>
<html>
<body>
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','PRIVATE','PRIVATE','PRIVATE');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?></body>
</html>
I've put PRIVATE where the database ID and password go for security reasons. Essentially, this PHP takes the value out of the 'wealth' column in according to the logged on user. I have this AJAX function that triggers this PHP (the ajax is located inside of the document I would like to send the PHP variable to). Note that this function sends the username of the current logged on user and their 'score' (the var clicks) to the PHP.
function sendScore() {
$.post("sendScore.php",{username:localStorage.getItem('userName'),wealth:clicks},function(response){
console.log("The service replied"+response);
});
}
Now, I know the value I retrieved is equal to the PHP variable $wealth. I also understand that PHP is server based and Javascript/html are client based, so you can't simply reach into another document and find the value of the variable. I'd like to assign the value of $wealth to a javascript variable named: userWealth
Thanks for reading!
EDIT: I WROTE THE Q WRONG ...
#Ilan Kleiman Small problem... I have two separate PHP files, sendScore and getScore. I had mistakenly pasted the wrong ones in the question. So, I have the sendScore AJAX which you can see in the question, but this triggers a different PHP code which isn't shown above, which essentially writes into the 'wealth' column. I have a separate piece of PHP, shown above, which is used to RETRIEVE written info from the wealth column (like how cookie clicker saves the number of clicks you have when you close the tab, this code activates when you open the website back up again, and it loads the last written value in 'wealth'). I am looking into how to create a piece of AJAX that can turn the $wealth PHP variable generated by the code into a javascript variable. Sorry for the confusion.
EDIT #2: CODE
AJAX FOR SENDSCORE
$.post("sendScore.php",{username:localStorage.getItem('userName'),wealth:clicks},function(response){
console.log("The service replied"+response);
});
PHP FOR SENDSCORE
<!DOCTYPE html>
<html>
<body>
<?php
$username = strval($_POST['username']);
$wealth = strval($_POST['wealth']);
$con = mysqli_connect('localhost','PRIV','PRIV','PRIV');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql = "UPDATE users SET wealth=".$wealth." WHERE username='".$username."'";
$result = mysqli_query($con,$sql);
}
mysqli_close($con);
?></body>
</html>
AJAX FOR GETSCORE IS WHAT I AM TRYING TO FIND
PHP FOR GETSCORE
<!DOCTYPE html>
<html>
<body>
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','PRIV','PRIV','PRIV');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?></body>
</html>
In your PHP file:
change
echo $wealth;
to
echo "<div id='wealth'>" . $wealth . "</div>";
AJAX Request:
var userWealth;
function getScore() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
userWealth = document.getElementById("wealth").innerHTML;
alert(userWealth);
}
};
xhttp.open("GET", "getScore.php", true);
xhttp.send();
}
This will set "userWealth" to $wealth from the PHP.
Keep in mind, the Javascript should be on the same "server/website" as the PHP otherwise the AJAX request won't work.

Trouble with php variables and ajax javascript

ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
first I have a php script on test.php on the apache server
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
I'm quite new so any advise would be appreciated, thanks.
The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object.
So first your JS code should be:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1 variable:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
so if we do this:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
You should define the PHP variable. And use that variable in your javascript:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>

How to use javascript in PHP? The script tag is not recognized

I don't know why but the script tag is not working, the SELECT query is working but i am not getting the prompt from the javascript.
it is not redirecting anywhere only a blank screen is seen
$qry1="SELECT area, aadhar FROM user where username='$user'";
$result1 = $connector->query($qry1);
if($result1){
$row1=mysql_fetch_array($result1);
$userarea= $row1['area'];
$useraadhar=$row1['aadhar'];
}?>
<body>
<script type="text/javascript">
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
if(inputarea==userarea){
<?php/
//date
$today = date("Y-m-d");
//Create INSERT query
$qry = "INSERT INTO complain (user,category,regno,course,lecturer,room,details,address,datein) VALUES ('$userid','$category','$reg','$coursename','$lectname','$roomno','$details','$address','$today')";
//$result = #mysql_query($qry);
$result = $connector->query($qry);
//Check whether difjslk the query was successful or not
if($result) {
$errmsg_arr[] = 'Complain succesfully added, please wait for your response';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: _new_complains.php");
exit();
}
header("location: _new_complains.php");
exit();
}else {
die("Query failed, couldn't add the new record");
header("location: _new_complains.php");
exit();
}
?>
}
You are sending data (for example body tag) before header(), therefore PHP creates an error. You just don't see it. Header needs to come before anything is sent to the browser (even a space).
You have multiple JS syntax errors:
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
Never EVER dump out raw text from PHP into a Javascript context. You're generating code that looks like
var inputarea=foo;
var userarea=bar;
var useradhar=baz';
The data will be seen as undefined variables, and you've got a stray ' in there. All of these errors will KILL the entire <script> block.
Always use json_encode() to dump from PHP->JS:
var inputarea = <?php echo json_encode($coursename); ?>;
This will GUARANTEE that you're producing correct Javascript code. The above line would produce
var inputarea = 'foo';
and be perfectly valid and executable code.

Categories