Refreshing a textbox every couple of seconds with mysql query? - php

I have this textbox in my code that everytime this page is loaded/refreshed, its content is filled with a query result. But since refreshing manually is not an option in my case, how can I do this automatically (I only want to refresh the textbox)? I've read about using AJAX, and I've been reading about it, but to be honest I don't quite get how to make it work, could someone explain me and dumb it down? Isn't there any easier way to refresh the textbox with the query content?
EDIT: Okay, I think I understood the basics of AJAX, the function is now refreshing the textbox every second, but there's a small problem. It messed up my table big time. I've modified the HTML code in hope someone can tell me what I did wrong. I'm thinking I shouldn't be including a div inside a table?
Here's how my table looked like and how it looks like after this little update
<?php
include '../Login/db_login.php';
session_start();
$sql = "SELECT Contador FROM senhas2 WHERE ID=1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$nome = $row['Contador']
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página de administração - A</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function(){
$('#refreshtb').load('bt1admin.php');
}, 1000)
</script>
</head>
<body>
<form action="" id="atender" method="POST">
<table border="1">
<tr>
<td>Clientes em espera:</td>
<td><div id="refreshtb"><input id="refreshtb" type="text" value="<?php echo "$nome";?>"readonly></div></td>
</tr>
<tr>
<td>Selecionar posto de atendimento:</td>
<td><select name="posto"><option value="n1" selected>1</option><option value="n2">2</option><option value="n3">3</option><option value="n4">4</option><option value="n5">5</option><option value="n6">6</option></select>
</tr>
<tr>
<td colspan="2"><input type="submit" form="atender" name="atender" value="Atender Cliente Seguinte"></td>
</tr>
</table>
</form>
</body>
</html>

You cannot change the content of a page using PHP. You'll need to use a front-end language, such as Javascript. Javascript is able to change your page's content, even after it is loaded. In order to update your page's content every X seconds, you'll want to use Javascript's setInterval() function to run a function every X seconds. This function would use AJAX to send a request to your website and gather some more data, and then update your textbox to contain this new data. You might find this Stackoverflow question helpful: How does AJAX work?
EDIT: To clear up some confusion in our comment discussion and in response to your edits, I've modified your code a little bit. Try this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página de administração - A</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax('bt1admin.php').done(function(data) {
$("#refreshtb").val(data);
})
}, 1000);
</script>
</head>
<body>
<form action="" id="atender" method="POST">
<table border="1">
<tr>
<td>Clientes em espera:</td>
<td><div><input id="refreshtb" type="text" value="<?php echo "$nome";?>"readonly></div></td>
</tr>
<tr>
<td>Selecionar posto de atendimento:</td>
<td><select name="posto"><option value="n1" selected>1</option><option value="n2">2</option><option value="n3">3</option><option value="n4">4</option><option value="n5">5</option><option value="n6">6</option></select>
</tr>
<tr>
<td colspan="2"><input type="submit" form="atender" name="atender" value="Atender Cliente Seguinte"></td>
</tr>
</table>
</form>
</body>
</html>
What I did:
First of all, you had duplicate #refreshtb elements, so I removed one of them.
You were also using the .load() method in JQuery. This does not update the value of an HTML input. Instead, it just replaces the child HTML, which is not what you want. I updated your script to now update the value of the #refreshtb input element.
Tested and it seems to work fine for me. If you're still getting that weird table issue after this or for some reason the field isn't being updated properly, I suspect it's an issue with your bt1admin.php page. Make sure that page isn't outputting the entire table, and instead just the value you want to go into the text box.

Related

How to store a multiple row query in a session var and use it with foreach

*I'm trying to carry my SQL query from PHP Controller file to my PHP View file. I've been cudgeling my brain for hours and hours. I've discovered that my major problem is that I don't know to carry data from PHP to another document that didn't start the REQUEST petition. The PHP Controller code (request) comes from a submit of other document (votar1.php).
I know to do it only if I pressed a button (type button) with onclick, but no idea when the code is triggered by submit button. Embbeding javascript on php doesn't works for me in any way.*
↓↓↓↓↓↓↓↓↓ (Focus on this better). ↓↓↓↓↓↓↓↓↓↓↓↓
Buuut, I think I'm close to the solution now, I've been experimenting with storing a query in a SESSION, so I would prefer this solution. It seems simple when the query returns you only one row, but when it returns more than one row, I don't know how to deal with it. So I need to know:
How to store multiple row query in a SESSION
How to use it (↑) to show data in a table using foreach.
I would be very thankful if you guide me a bit about these 2 things mentioned above ↑ (please, don't forget about the second one, because I don't know how to deal with that).
Controller(controladorPartidos.php):
include 'conexionBBDD.php';
session_start();
----other code----
if (passwordMatch($nif, $password) && (!haVotado($nif))) { //si la contraseña es correcta y no ha votado...
$consulta = "SELECT LOGO, NOMBRE FROM partido";
$resultado = $conexion->query($consulta);
while ($rows = mysqli_fetch_assoc($resultado)) {
$query=array_push($_SESSION['query'], $rows);
}
header('Location: Vista/votar2.php');
}
PHP View (votar2.php):
<?php
include_once 'header.html';
session_start();
$query = $_SESSION['query'];
?>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="javascript.js"></script>
<title></title>
</head>
<body>
<div id="caja">
<form action="../controladorPartidos.php" name="formVotar2" id="formVotar2" method="post">
<table>
<?php foreach ($query as $partido) { ?>
<tr>
<td style="text-align: center"><img src="<?php echo $partido[0] ?>"/></td>
<td><input type="radio" name="partido" value="<?php echo $partido[1] ?>"><?php echo $partido[1] ?></td>
<?php }; ?>
</tr>
</table>
<div style="width:75px; margin-right:auto; margin-left:auto;">
<br/>
<input id="botonVotar" type="submit" name="submit" onClick="submitVoto()" value="Votar"/>
<br/>
</div>
</form>
</div>
</body>
</html>
I hope you can help me! Thank you in advance for your time :)

PHP form pop-up for confirmation request

I would like to implement a pop-up request for the user , e.g. if the user press "yes" for confirm data on MySQL DB are modified otherwise no. This should be done without creating another php confirmation page. I looked through forum discussions , I founded some possible solutions based on Ajax or Javascript but unfortunately I don't know how to programme with these tools.
Can anyone helps?
many thanks
//$sql_select= "SELECT .... FROM DB
}
//------------------Button save data pressed--------------------
if (isset($_POST['bottone_update'])) {
// If te user click confirm button I have to modify the database
/*$sql_upd = "UPDATE db_sale.prenotazioni_alpha SET VALUES.....*/
}
?>
<html>
<head>
</head>
<style type='text/css'>
<meta charset="utf-8">
</style>
<body>
<form method="post" action="">
<!--Table data -->
<table class='table1' id="pos_table1">
<tr>
<td><textarea name="alpha_9_10"></textarea>
<td>
<td><textarea name="meda_9_10"></textarea>
<td>
</tr>
<tr>
<td><textarea name="alpha_10_11"></textarea>
<td>
<td><textarea name="meda_10_11"></textarea>
<td>
</tr>
</table>
<button type="submit">look for data</button>
<button type="submit">Save data</button>
You can simply add an onSubmit attribute to the form, with the JavaScript function confirm in it. It will open a pop-up in the browser, asking whatever you define within the first parameter, with two buttons: "OK" and "Cancel". This has the feature of returning true or false (a boolean), when clicking "OK" or "Cancel" respectively.
This means that if you do onSubmit="return confirm('Are you sure?');" in the form, you'll be able to send the form only if you press "OK" to this check. Then, in PHP, you just check weather or not the form has been submitted; and if it has - you perform your update-query, like you already started doing - no need for additional checks!
if (isset($_POST['bottone_update'])) {
// Perform your query
}
Your opening <form>-tag should then contain this:
<form method="POST" onSubmit="return confirm('Are you sure?');">
<!--- Rest of form goes here -->
</form>
If you have action="", you can just remove it altogether.
Try This:
$('#button').click(function () {
if (confirm('Are You Sure?')) {
$.post('http://localhost/ajax.php', function () {
alert('Data Added Successfully!');
});
}
});

AJAX request callback using jQuery

I am new to the use of jQuery for handling AJAX, and have written a basic script to get the basics down. Currently I am POSTing an AJAX request to the same file, and I wish to do some additional processing based on the results of that AJAX call.
Here is my code:
**/*convertNum.php*/**
$num = $_POST['json'];
if (isset($num))
echo $num['number'] * 2;
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
td {border:none;}
</style>
</head>
<body>
<table width="800" border="1">
<tr>
<td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
<td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
</tr>
<tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
</table>
<script>
$(document).ready(function () {
$('#getNum').click(function () {
var $numSent = $('#numSend').val();
var json = {"number":$numSent};
$.post("convertNum.php", {"json": json}).done(function (data)
{
alert(data);
}
);
});
});
</script>
</body>
</html>
Here is the response I get if I submit the number '2':
4
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
td {border:none;}
</style>
</head>
<body>
<table width="800" border="1">
<tr>
<td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
<td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
</tr>
<tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
</table>
<script>
$(document).ready(function () {
$('#getNum').click(function () {
var $numSent = $('#numSend').val();
var json = {"number":$numSent};
$.post("convertNum.php", {"json": json}).done(function (data)
{
alert(data);
}
);
});
});
</script>
</body>
</html>
Obviously I'm only interested in receiving and using the number '4', hence my question: What is the best way to specify exactly what data I want returned?
Some thoughts I've had:
wrapping all my HTML inside a if statement (i.e., if $num isset, do NOT output html; else output HTML) but then I'm echoing HTML, and I'd rather not do that.
Setting up a separate PHP script to receive my AJAX call: That was what I did originally, and it works just fine. However, I am interested in keeping everything inside one file, and wanted to explore possible ways of doing so.
I'm sure there is an elegant way to do this. Thanks for any suggestions!
The elegant way would be to have a separate(!) PHP file that will only output the number times 2 part of your current PHP. Then you generate an AJAX request from your current PHP to the new separate PHP.
I believe this post answers one aspect of what you are seeing - the echoing of the entire page in your alert box.
Next, here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
You could add die(); after you echo the number if you really want to keep it on the same page. This will terminate the execution of the script. Don't forget to add brackets around the if statement:
if (isset($num)) {
echo $num['number'] * 2;
die();
}
It is, however, not the most elegant solution.
NOTE *The better approach is to keep things like this in a separate file, makes it easier to read and easier to understand, especially if you use a good naming conversion.
It is a bad procedural approach but here I go :) :
<?php
$num = $_POST['json'];
if (isset($num))
echo ($num['number'] * 2);
die();
?>
or better yet:
<?php
$num = $_POST['json'];
if (isset($num))
die($num['number'] * 2); //In case of error you could put them in brackets
?>
PS
As alternative to die(); you could use exit();, they both do pretty much the same: terminating further execution
I don't know how efficient this is but you can do something like:
<?php
/*convertNum.php*/
$num = isset($_POST['json']) ? $_POST['json'] : NULL; //you have errors in this line
if (!is_null($num)){
echo $num['number'] * 2;
exit(); //exit from script
}
?>

Assistance with FORM-SUBMIT & "?" removal from URL

I was wondering how one would go about sending whatever the user types in text box; to the end of the <form action=. If one does not have access to the websites code source, how would one go about this?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
a:link {color:#687BC6;}
a:visited {color:#0F0;}
a:hover {color:#000;}
a:active {color:#0A0;}
</style>
</head>
<body>
<form name="form1" method="get" action="http://www.blah.com/right-now/" target="_blank">
<table border="0" cellpadding="2" cellspacing="0">
<tr><td>ZC:</td>
<td><input name="fld-zip" type="text" maxlength="7" size="15"></td></tr>
<tr><td> </td>
<td><input type="submit" name=Submit value="Submit this"></td></tr>
</table>
</form>
</body>
</html>
Pretty much asking how you can add what you put in text box to the end of URL /??? when you click the submit button.
So it shows:
Textbox - "11722"
URL = http://www.blah.com/right-now/11722
Is there a way to do this via css/html/php/js?
Every time I click the SUBMIT button, it just adds a '?' at the end and it gets cut off.
Well,m just giving it a try...i dunno whether it'll work or not.. do one thing,use two files..one to get the zip code..
=>in file 1,use a form.. after submitting,send the zip code to a dummy file(second file) i.e.,action="dummy.php"
=>in dummy file assign the zip code to a variable '$a'
$a=$_GET['zip'];
now use javascript
<script>
function a()
{
newwindow=open("http://www.blah.com/rightnow/'$a'",window,"height=900,width=1100");
}
</script>
I would do something like this at the top of the page.
<?php
if (!(empty($_GET['fld-zip']))){ //check if the var is empty
$url = "http://www.blah.com/right-now/";
$page = $_GET['fld-zip'];
header("location:$url . $page"); //if its all good then redirect to the correct page
}
?>
This could probably be done a bunch of different ways but should work.
The ? is there because the form is submitted using get it wont go away and shouldnt. Do some reading on GET and POST in HTML forms.
if you use GET, the link should look something like "http://www.blah.com/right-now?variable1=11722&variable2=11733. The question mark is at the beginning of the variables. How does it get cut off?
If you're using http://www.blah.com/right-now/ as the action, make sure that http://www.blah.com/right-now/index.php has the logic.
As your basically wanting to just open a new window with the value of what's entered in the text box concatenated on to a url;
Change your form slightly, use a button instead of a submit, and with the use of jquery(cleaner imo) and a simple js function to put it altogether & trigger it from the forms onClick="doForm()".
<script>
function doForm(){
var param = $("#fld-zip").val();
window.open ("http://www.blah.com/right-now/" + param,"openwindow");
}
</script>
<form name="form1" method="get" action="" target="_blank">
ZC:<input name="fld-zip" id="fld-zip" type="text" maxlength="7" size="15">
<input type="button" name="Submit" onClick="doForm()" value="Submit this">
</form>
Add a script like this
function formSubmit(){
document.getElementById('frm1').setAttribute('action', "http://www.google.com/right-now/" + document.form1["fld-zip"].value)
document.form1["fld-zip"].value = '';
return true;
}
then add onsubmit event to your form
<form id="frm1" name="form1" method="get" action="http://www.blah.com/right-now/" target="_blank" onsubmit="return formSubmit()">
Working example http://jsfiddle.net/FtRKp/4/

Submit Search query & get Search result without refresh

I want to submit search query form & get search result without redirecting/reloading/refreshing on the same page.
My content is dynamic so can not use those "submit contact form without refreshing page which replies back on success".
In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:
Use Ajax to Post the data from your form to a php file;
That file in background will query the database and obtain the results for the data that he as received;
With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;
At last, you need to set some controlling stuff to let styles and document workflow run smoothly.
So, having said that, here's an working example:
We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a div with a table with pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="pt" dir="ltr">
<head>
<title>Search And Show Without Refresh</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<!-- JQUERY FROM GOOGLE API -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
</head>
<body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
HEADER
</div>
<div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
<div id="search_results"></div>
</div>
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
FOOTER
</div>
</body>
</html>
db_query.php
<?php
define("HOST", "localhost");
// Database user
define("DBUSER", "username");
// Database password
define("PASS", "password");
// Database name
define("DB", "database_name");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM persons
WHERE age='".$_POST['value']."'
");
echo '<table>';
while ($data = mysql_fetch_array($query)) {
echo '
<tr style="background-color:pink;">
<td style="font-size:18px;">'.$data["name"].'</td>
<td style="font-size:18px;">'.$data["age"].'</td>
</tr>';
}
echo '</table>';
?>
The controlling stuff depends from what you want, but use that code, place those two files in the same directory, and you should be fine!
Any problems or a more explicative code, please let us know ;)
You'll probably want to start with any of the thousands of "AJAX for beginners" tutorials you can find on the net. A Google search with that term should get you going.
Try this for starters:
http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html
After you've read through that, keep in mind that you really don't need to be writing any XHR handling code. As pointed out by Jamie, jQuery or any of the other multitudes of Javascript libraries out there, can greatly simplify your client-side AJAX code.
This is what AJAX is for.
In jQuery (apologies if you're looking for a different library)
$("form#search").bind('submit',function() {
$.post("search.php",this.serialize(),function(data) {
// Put the code to deal with the response data here
});
return false;
});
It's good if you can get some basics of Ajax before straight away going to the code.
Ajax , is the exact solution for your problem. It asynchronously makes a request to the server, get the result and the data in the page can be modified with the result . It's all done in JavaScript.
Suppose you have an html like this:
<html>
<body>
<div id="myDiv"> your content area</div>
<button type="button" onclick="loadByAjax()">Change Content</button>
</body>
</html>
Now, your javascipr code will be like this:
<script type="text/javascript">
function loadByAjax()
{
$.ajax({
type: "POST",
url: "yourserverpage.php",
data: "searchkey=data_from_user_input",
success: function(response_data){
$('myDiv').html(response_data)
}
});
}
</script>
so, basically upon click of the button, the JavaScript will be executed. It wil call the php serverside script, pass the parameters it got from user input and retrieve the response data and place it inside the div.
So your page is updated without full refresh.
Also, please understand that, i used jquery library here for the Ajax function.

Categories