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

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");

Related

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.

Registration form isn't properly Connecting to MySQL

Ok, so I've successfully linked a Contact Form for my website to a MySQL database and I'm super stoked about figuring it out, however on my registration page my code isn't working. I ran this connection check:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "It's Working!";
}
and it says: "It's working!" So i know i've established a connection to my SQL database.
Let me try to clarify further:
I've got 2 main files for this particular program (obviously we won't be needing to care about styles.css or the linked files for other pages in my site): register.php and db.php. Here is my code for both. It's simply a project website so i don't care if people see/use my code... It's not working anyway so knock yourselves out, LOL!
First, db.php:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'forms1');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
Now here's the php in register.php, which I've place at the top BEFORE any HTML at all:
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$lname = $_POST["lname"];
$a1 = $_POST["a1"];
$a2 = $_POST["a2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$lname = mysqli_real_escape_string($db, $lname);
$a1 = mysqli_real_escape_string($db, $a1);
$a2 = mysqli_real_escape_string($db, $a2);
$city = mysqli_real_escape_string($db, $city);
$state = mysqli_real_escape_string($db, $state);
$zip = mysqli_real_escape_string($db, $zip);
$phone = mysqli_real_escape_string($db, $phone);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users(name,lname,a1, a2, city, state, zip, phone, email, password) VALUES ('$name', '$lname', '$a1', '$a2', '$city', '$state', '$zip', '$phone', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
mysqli_close($db);
I should probably mention that JavaScript is included in the HEAD section of my HTML:
(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)
$(document).ready(function() {
$('form.required-form').simpleValidate({
errorElement: 'em',
ajaxRequest: true,
completeCallback: function($el) {
var formData = $el.serialize();
}
});
});
$("form[name='form1']").submit(function(){
.... JS code ....
return error;
});
</script>
<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};
Well, I tried to include the HTML code for the form but it wasn't appearing properly, but believe me when i tell you that ALL the inputs of the the form fields have a name="" that corresponds to the fields within my table within my database within MySQL. The HTML is most certainly not the problem. I've check syntax and spelling over and over. It's not the HTML. Somewhere there is an error, though.
PLEASE HELP!!!
Thank you all very much.
-Maj
P.S. I purposely deleted the opening and closing php/html tags here in these examples so it'd be easier to read, but i have them placed in my original code.
After that if($query){ } block try adding else { print(mysqli_error($db)); }
perhaps there's an error, but what is the response you got from register.php?
you should start to debug your source code, but if you don't use a debugger, put some "die(SOME VARIABLE);" to locate your trouble area and without javascript, for the first. Just use some simple html-formular and to get row datas, put the answer into <PRE> tags ( or use curl in a terminal, i like this way, but for you it is not necessary ).
If you don't debug your php-code or you your browser-relevant-code, means "html, css, javascript, ..." (you can see with firebug, what data you are sending and what is coming back), you can use echo "INSERT .... BLA ...$VAR ...;" and copy-paste the SQL-Statement and testing it in PhpMyAdmin, to see you get a proper statement, maybe there is a type-converting-problem or many other thinks are possible.
If everything is going well, it is probably some trouble in your javascript-code. But probably you need to convert a type of some variable, you should copy and paste your SQL-Statement and execute it in phpmyadmin to make a verification of your SQL-Statements which you put in your Php-Code. Cheers.

Using json_encode without displaying it on my webpage via echo or print

basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);

Accessing MySQL database in d3.js with php file

I need some help with MySQL and D3 with a php file.
I am trying to get access to my database using D3. I have created a php file where I make the connection to MySQL.
My problem is however that I get an empty array when printing out my output to the console from D3. I can't seem to find what I am doing wrong. Below is my code for both the D3 call and the php file: (I have appropriate names from username, password and database name.)
<?php
$host = "localhost";
$port = 8889;
$username = "********";
$password = "********";
$database="***datebasename***";
if (!$server) {
die('Not connected : ' .mysql_error());
}
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
if (isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "null";
echo "Type not passed";
}
if($type=='load'){
$string = '';
$gene = $_GET["gene"];
$data = $_GET["data"];
$myquery = "select gene_data.gene_data from genes inner join gene_data on genes.id=gene_data.g_id where genes.name ='$gene' and genes.type='$data'";
$query = mysql_query($myquery);
if ( !$myquery || !$query) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
}
?>
My file are all running from a server. The MySQL server is also on the same server, so I jut call localhost to get access. Also since I need several different parameters for my SQL calls I send the values from D3 ("gene" and "human").
The following the call I make from D3:
d3.json("getdata.php?type=load&gene=CLL5&data=human", function(error, data) {
console.log(data);
});
Also it is worth mentioning that my query is tested and works.
Some help would be greatly appreciated! Any ideas on how to debug with and prints or write.outs would be appretiated as well!

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