Check if MySQL is still connected or disconnected - javascript

Basically, what i'm trying to do in pseudo-code is this:
if button_1_press {
if connection_doesnt_exist{
create_connection
echo "connected"
}
else {
echo "still connected"
}
}
if button_2_press{
if connection_exist{
close_connection
echo "disconnected"
}
else {
echo "still disconnected"
}
}
I tryed some approaches, the best i have so far is this:
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type='text/javascript' src='script.js'></script>
<title>PHP AJAX Example</title>
</head>
<body>
<input type='submit' onclick='makeRequest();' value='Connect' id='b1'/>
<input type='submit' onclick='makeRequest();' value='Disconnect' id='b2'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
Javascript:
var xmlHttp = createXMLHttpRequest();
function createXMLHttpRequest(){
var xmlHttp;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlHttp = false;
}
}
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
function makeRequest(){
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
HandleResponse();
}
}
document.getElementById("b1").onclick = function () {xmlHttp.open("GET", "mysql.php?button=1", true); xmlHttp.send(null);}
document.getElementById("b2").onclick = function () {xmlHttp.open("GET", "mysql.php?button=2", true); xmlHttp.send(null);}
}
function HandleResponse(){
response = xmlHttp.responseText;
document.getElementById('ResponseDiv').innerHTML = response;
}
PHP
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
if ($_GET['button']==1){
if ($conn){
echo "already connected";
}
else {
$conn = new mysqli($servername, $username, $password);
echo " connected";
}
}
if ($_GET['button']==2){
if ($conn){
echo "disconnected";
$conn->close();
}
else {
echo "still disconnected";
}
}
?>
My problems are:
1) When any of the buttons is clicked for the first time, it does nothing; only starts working from the second click.
2) Button "Connected" always shows "already connected".
3) Button "Disconnect" always shows "disconnected"
What I understand is this happen because every time a button is pressed, the makeRequest function makes an AJAX call, which creates a mysqli connection every time, so at the moment of evaluate if its open, it always will be true, but I have no idea how to fix it.

This totally pointless.
By default PHP shuts down/cleans up all open connections when a script exits. So every time you do an AJAX request to test the db connection, you'd be opening a NEW database connection anyways, never testing a previous connection.
You COULD use persistent DB connections, but even with that there's no guarantee you'd get the SAME connection as you got last time. You'd get some randomish connection from a pool of open connections, which against is pointless to test.
And going with persistent connections opens a huge pile of problems as well. The microscopic benefits of going persistent is vastly dwarved by all the problems it'll cause.

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

How can I keep PHP session alive with AJAX in native JS?

My HTML file calls functions on the JS file which pass parameters to the PHP file to call specific functions. My problem is that I would like the PHP session to stay alive so that when the user calls the login function, the $connection variable stays alive and can be used when the user eventually calls the loadBD function and Ajax calls the PHP file, the $connection variable is empty. I know I could use a file with the login details and include it at the start of the PHP file, but that won't work, because I don't know the details yet. How can I only login once?
Here is the JS file:
function runScript(params) {
xhr = new XMLHttpRequest();
xhr.open('POST', 'scripts.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("demo").innerHTML = xhr.responseText;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(encodeURI(params));
}
function login() {
var params = "func=login";
params += "&svr=" + document.getElementById('srv').value;
params += "&name=" + document.getElementById('name').value;
params += "&psw=" + document.getElementById('psw').value;
;
runScript(params);
}
function loadBD() {
var params = "func=load_db";
runScript(params);
}
Here is my PHP file:
<?php
$func = $_POST["func"];
$connection;
switch ($func) {
case 'login':
login();
break;
case 'load_db':
load_db();
break;
default: echo 'Function Error';
break;
}
function login() {
$connection = #mysqli_connect($_POST["svr"], $_POST["name"], $_POST["psw"]) or die("initial host/db connection problem");
if(errorCheck($connection)) {
getDatabases($connection);
}
}
function errorCheck($connection) {
if (!$connection) {
echo "internal error " . mysqli_errno();
return FALSE;
} else {
return TRUE;
}
}
function getDatabases($connection) {
$result = mysqli_query($connection, "SHOW DATABASES");
$available = array();
$index = 0;
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0];
$available[$index] = $row[0];
$index += 1;
echo "<a href='javascript:loadDB();' >Load $row[0]</a>";
echo "<br>";
}
}
}
function load_db() {
echo "loading";
echo $connection;
}
?>
This is extremely insecure and a very bad idea. You are exposing your database credentials to the world on your web page. Standard practice is to store your database configuration in a secure location on your server and reference that config file directly from PHP.
Keeping database connections alive between requests is separate from PHP sessions. It depends very much on the details of your setup, so see the official docs for details.
PHP sessions themselves are "alive" in the sense they are tracked across requests via the session cookie. As long as the same cookie exists and the session hasn't expired, you do not need to do anything extra to keep it "alive".
You can't keep the connection open between requests; that's not really how PHP works (by default, anyway). What you could do is store the connection details for the user session in PHP's $_SESSION and use that to reestablish the connection to the database when the user hits your PHP script.

Error when trying to call javascript function

I'm trying to add a listener into the 'Yes' button which is shown in the code below.I want this function to save this boolean value into approval field in my database like:$query_row['approval']==1; and a message to display on it.But when executing the code nothing happens after clicking on the'Yes button'.
Can someone please show me how to fix this code if there is an error on it?
Thanks in advance!
This is my code:
<html >
<head>
<title></title>
</head>
<body>
<?php
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
$result = mysql_query("SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
// if($_POST['admin']==0) {//perjashton administratorin
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
//nese esht aprovuar logini i st.
echo "You are approved";
}
else //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br />";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?
<button id="but">Yes</button><button>No</button><br />
<p id="demo"></p>';
?>
<script>
document.getElementById("but").addEventListener("click", MyFunction());
function MyFunction() {
$query_row['approval']==1;
document.getElementById("demo").innerHTML = "This account is approved";}
</script>
<?php
}mysql_close($database);
?>
</body>
</html>
And this is my database with the approval field which boolean value I'm trying to change:
Change document...addEventListener("click", MyFunction()); to document...addEventListener("click", MyFunction); otherwise your function executes immediately and only once.
You can't modify a value in the database only with changing value of the output array. You have to create a new php file and call it asynchronuslly. Read more about updating values in the database here and about calling files asynchronuslly here.
First, I will edit your main file because it's a mess (sorry to say that, but don't worry, it was same with me):
<html>
<head>
<title></title>
<script>
function MyFunction(id) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText.indexOf("UPDATE WENT OK")!=-1)
document.getElementById(id).nextSibling.innerHTML = "This account is approved";
}
else {
document.getElementById(id).nextSibling.innerHTML = "An error occured while approving this account";
}
}
xhttp.open("GET", "ajax_file.php?id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
print("Could not connect");
else {
$result = mysql_query($database,"SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
//nese esht aprovuar logini i st.
echo "You are approved";
}
else { //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br/>";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?';
?><div class="container"><button id="<?php echo $query_row['id'];?>" onclick="MyFunction(this.id)">Yes</button><button>No</button><br />
<p class="demo"></p></div><?php
}
}
}
}
mysql_close($database);
?>
</body>
</html>
Now, create a php file named ajax_file.php (in the same folder):
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
die("Could not connect");
else {
$id = intval($_GET['id']);
$result = mysql_query($database,"UPDATE table `login` SET approval = 1 WHERE `id` = '".$id."'");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
echo "UPDATE WENT OK";
}
Do not hesitate to ask me about any detail how this works. Also, this might not be correct because i don't exactly know what you are doing or want to do with the file you provided. But, if you'll give me the details, I will edit it so it will work.

Is it possible to call PHP-Script from JavaScript section of JSP page..?

I have written following script on server-
<?php
//Create an array
$json_response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$status = "In Progress";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$con)
{
die('Could not connect to database: ' . mysql_error());
}
//Query to select pending queries database
$result = mysqli_query($con, "SELECT * FROM tbl_query_master WHERE status='".$status."' ORDER BY query_date DESC");
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row_array['query_id'] = $row['query_id'];
$row_array['sender_mobile_no'] = $row['sender_mobile_no'];
$row_array['sender_name'] = $row['sender_name'];
$row_array['query_string'] = $row['query_string'];
$row_array['action_taken'] = $row['action_taken'];
$row_array['status'] = $row['status'];
$row_array['query_date'] = $row['query_date'];
$row_array['action_date'] = $row['action_date'];
$row_array['view_status'] = $row['view_status'];
$row_array['read_status'] = $row['read_status'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
Above script returns one JSON object which is useful for me in JavaScript section of my JSP page, but I don't know how to call php-script from the java script section, so need your guidance for the same. Hope you understand what I'm saying Thank you..!
Suppose your php script is deployed to a web server (apache with php mod) and is triggered by some URL, e.g. http://localhost/script.php
Then in your javascript you can do POSt request using jquery:
$.getJSON('http://localhost/script.php', function(json) {
// do what you need with your json data
});
Finally I solved it using AJAX as follows, I don't know whether performance wise this method is correct or not, but perfectly worked for me. Write the following code in your JavaScript section.
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function getDataChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether server response came back with no errors.
{
//THE RESPONSE FROM SERVER. DO YOUR STUFF WITH xmlHttp.responseText
alert("Responce= "+xmlHttp.responseText);
//document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function getData()
{
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "http://yourdomain.com/your_script.php"; // URL of server-side resource.
// Using following way you can send parameter to your script.
//url += "?param1=" + param1 + "&param2=" + param2;
xmlHttp.onreadystatechange =getDataChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
And finally create event to call "getData()" function. That's it. Thank you..!

JS bug: input field repeated with xmlhttp response text

This is a follow up of another question I asked last night. My problem now is not that the script doesn't works, but that I'm getting some very strange repeat of an HTML input element when my xmlhttprequest object returns the response text. Here's the code:
<!DOCTYPE HTML>
<?php
if(!empty($_GET['uName']))
{
$r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
mysql_select_db("db", $r) or die ("Couldn't select db");
$q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
$data = mysql_fetch_assoc($q);
mysql_close($r);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="fUName" onchange="ShowUser(fUName.value);" value="name" style="width:125px;">
</form>
<div id="display"><?php print "ID = {$data['id']}"; ?></div>
</body>
</html>
<script type='text/javascript'>
function ShowUser(name)
{
if(name.length == 0)
{
document.getElementById("display").innerHTML = "Please enter a username to check";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "index.php?uName=" + name, true);
xmlhttp.send();
}
</script>
Here's the strange problem:
There should only be one input field, and is orginally, however when I enter text into it and it loses focus, the JS is triggered and also prints out another input field.
Please ignore the bad practice of PHP, JS and HTML/CSS in one script, this was supposed to be a quick test that has turned for the worse :)
I'm baffled!
Thanks for any help.
The problem lies in the fact that all of your code is in one page. Consider this: you load up index.php. After it's all displaying then you call this same page again (for your AJAX request) so you're essentially saying "Hey, I want you to try and load this page again," hence why you're ending up with duplicate fields.
Try separating out your files in to something like index.php and getuser.php or something of the sort.

Categories