Sending value of PHP variable to Javascript document - javascript

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.

Related

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

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.

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.

Fetching & displaying data from a database (Javascript XML HTTP Request)

I’m really struggling with this task for my course and hope someone doesn’t mind helping out or just offering guidance here. Basically I’m trying to create a simple Javascript XML Http Request to display basic information (the country_name & country_capital fields) from the database just in the html page. Below I just describe the apparent stages from the guide, and what I have done.
Firstly the ‘database.html’ page contains javascript XHR code which I think is mostly correct, but may have an error. To be honest I’m not 100% sure what else it does other than somehow refer to the getcountries.php file.
Secondly the getcountries.php file is where I’m really struggling as I’ve never coded in PHP. I think it’s supposed to fetch the data from the local server (I’m running XAMPP) and echo the results on the web page.
The database on phpMyAdmin is simple with just a table of countries including a primary key ID number, the country name, capital and currency, with the details below:
Database name = countries_db
Table name = countries_table
Table fields:
country_ID (primary key)
country_name
country_capital
country_currency
An example entry: 2, USA, Washington DC, US Dollar
To summarise, my question is this: how can I edit what I’ve done to correctly fetch the data from the database and display it on the page?
Really appreciate any help or advice here, thanks a lot.
<!-- Code on Page 1 (database.html) -->
<p id="txtHint"></p>
<p id="hint"></p>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // detects whether the browser has XMLHttpRequest functionality
// code for modern browsers
xmlhttp=new XMLHttpRequest(); // creates an XMLHttpRequest object
} else { // code for old browsers
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() { // onreadystatechange defines the function to be called when the readyState property changes
if (this.readyState==4 && this.status==200) {
document.getElementById("hint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcountries.php?q="+str,true);
xmlhttp.send();
}
</script>
<!-- Code on Page 2 (getcountries.php) -->
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' .mysqli_error($con));
}
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
$result = mysqli_query($con,$sql);
echo "Results:"
error_reporting(E_ERROR | E_PARSE);
\
while($row = mysqli_fetch_array($result)) {
echo $row['country_name'] . "<br>";
echo $row['country_capital'] . "<br>";
}
mysqli_close($con);
?>
Assuming that this is the structure of your data base:
Database name = countries_db
Table name = countries_table
Table fields:
country_ID (primary key)
country_name
country_capital
country_currency
The problem is that you have some syntax error in your code change this lines:
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
with:
mysqli_select_db($con,"countries_db");
$sql="SELECT country_name, country_capital FROM countries_table";
Alternative: using PDO:
Try this instead of your getcountries.php implementation
<?php
$driver = 'mysql';
$database = "dbname=countries_db";
$dsn = "$driver:host=localhost;unix_socket=/home/cg/mysql/mysql.sock;$database";
$username = 'root';
$password = 'root';
try {
$conn = new PDO($dsn, $username, $password);
echo "<h2>Database countries_db Connected<h2>";
}catch(PDOException $e){
echo "<h1>" . $e->getMessage() . "</h1>";
}
$sql = 'SELECT country_name, country_capital FROM countries_table';
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Results:";
echo "<table style='width:100%'>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
foreach($row as $value)
{
echo sprintf("<td>%s</td>", $value);
}
echo "</tr>";
}
echo "</table>";
?>
Use mysqli_select_db instead of mysqli_select-db in your getcountries.php:
mysqli_select_db($con,"countries_db");

Auto load search results when page loads

I am using a joomla module i would like to modify to auto load the default list of results.
currently, when the page loads no result is shown. If all search fields are empty and the user clicks the search button, the page will load all data. If information in placed in the search fields, the results will be broken down to match what was typed in.
I want the page to auto load all data when the page loads without the user clicking search.
How do i achieve this?
I believe the module uses ajax and i believe the info that affects this is below:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html');
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
ini_set("display_errors", "On");
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
$my_path = dirname(__FILE__);
$my_path = explode(DS.'modules',$my_path);
$my_path = $my_path[0];
if (file_exists($my_path . '/defines.php')) {
include_once $my_path . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', $my_path);
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
///////////////////////////////////////////////////////////////////////////////////////////////
$name = $_GET['name'];
$value = mb_strtolower($_GET['value']);
$next = mb_strtolower($_GET['next']);
$db = JFactory::getDBO();
$query = "SELECT * FROM #__k2_extra_fields WHERE published = 1";
$db->setQuery($query);
$results = $db->loadObjectList();
$extra_val = '';
$extra_id = 0;
foreach($results as $result) {
if(trim(mb_strtolower($result->name)) == trim($value) . " " . trim($next) || trim(mb_strtolower($result->name)) == trim($next) . " " . trim($value)) {
$extra_val = $result->value;
$extra_id = $result->id;
break;
}
}
require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
$json = new Services_JSON;
$extra_val = $json->decode($extra_val);
if($extra_val != '') {
foreach($extra_val as $val) {
echo "<option>" . $val->name . "</option>";
}
echo "<option>".$extra_id."</option>";
}
?>
Please help!
to auto load search result we must need to store search query in session variable,
http://docs.joomla.org/How_to_use_user_state_variables
http://docs.joomla.org/API15:JApplication/getUserStateFromRequest
This are the links which will describe very well about how to manage request variable in session, so there is no variable in request it will get value from the session.
try to use something like this
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
then you can easily change myFunction to trigger your search on click event
<script>
function myFunction()
{
document.getElementById('YOUR-BUTTON-ID').onclick();
}
</script>

Two questions about possible mysql and php functionalities (maybe javascript?), and where I should look to learn more

First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>

Categories