Read new update from database and then execute PHP code - AJAX - javascript

I'm currently studying a telegram chatbot and I got this idea that I want the bot to send only new data if there is new data in my database which is MySQL and it won't execute the PHP code if there is no new data. But I can't figure out how to do it, for now, I use the meta http-equiv= "refresh". Is there any other method that does something that I need to implement?
I tried to use AJAX long polling method but I don't really understand how to implement it on my project, but I think it might solve my problem. And I already tried to auto-refresh the page every 10 minutes, it works but it will spam the chat with the same data every 10 minutes if there is no new data.
For now this is my code for executing the chatbot so that it will send my data.
<?php
$orang = $db->query('SELECT time_stamp,group_name, message, nvalue, old_svalue, inactive_timestamp, ack_timestamp
FROM alarm ORDER BY time_stamp DESC LIMIT 2');
//$arrayAll = [];
foreach($orang as $orn){
$data = implode(" ",$orn);
$arrayAll[] = $data;
}
//new update function
//execute dibawah
if($orn["nvalue"] < 30){
echo "Tidak dikirim";
}else{
$arrayAll = implode("\n", $arrayAll);
$response = $telegram->sendMessage([
'chat_id' => "$idChat",
'text' => "\n$arrayAll",
'parse_mode' => 'HTML'
]);
}
?>
This is my HTML for showing the data on the database
<body>
<table>
<tr>
<th>Message</th>
<th>Group Name</th>
<th>Time Stamp</th>
</tr>
<?php
foreach($orang as $org){
?>
<tr>
<td>
<?php echo $org["message"];?>
</td>
<td>
<?php echo $org["group_name"];?>
</td>
<td>
<?php echo $org["time_stamp"];?>
</td>
<?php
}
?>
</tr>
</table>
</body>
Thank you.

Related

How to get the specific data from postgresql database when an user logs in after admin assigning the data using codeigniter?

I'm making project where i have 1 admin & 10-15 users.
For each user, I want to only show to them the cases specifically assigned to them to load on their dashboard when admin assigns them. cases that was not assigned to them will not be listed on their dashboard.
Admin can successfully assign case_id to a table
Here is the case_assignment table which has case_id (which the admin assigns), username (to whom the case assigned), assigned date.
similarly users table there is username,password,level(admin is 1 and all other user are 2),email
if the admin had assigned the case (case_id will be present) to particular username in case_assignment table, then, when user logins, he should be able to see all the data (tables) related to that particular case_id.
here are screenshot:
Admin page: https://prnt.sc/novscc --> this how the datatable will be displayed for admin.. he will be having all case data. when he assigns case to user. user should receive only that case.
User page: https://prnt.sc/novtnr -> this is how i want user datatable to be displayed when admin assigns a case.
Here is the database case_assigment table screen shot : https://prnt.sc/novtze (here only case_id & username to whom admin wants to assigns will be there).
Here is the view, user.php
<table id="table" class="table table-striped table-bordered display nowrap" cellspacing="0" width="100%" "style="width: 650px;">
<thead>
<tr>
<th>Case ID</th>
<th>Case Name</th>
<th>Firm Name</th>
<th>Case Overview</th>
<th>Priority</th>
<th>Received Date</th>
<th>Expected Delivery Date</th>
<th>Service Status</th>
</tr>
</thead>
<tbody>
<?php
if($result){
foreach ($result as $results) {
?>
<tr>
<td><?php echo $results->case_id; ?></td>
<td><?php echo $results->case_name; ?></td>
<td><?php echo $results->firm_name; ?></td>
<td><?php echo $results->case_description; ?></td>
<td><?php echo $results->priority; ?></td>
<td><?php echo $results->received_date; ?></td>
<td><?php echo $results->expected_delivery_date; ?></td>
<td><?php echo $results->service_status; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
Here is my Controller (employee.php)
public function index()
{
$this->load->helper('url');
$this->session->userdata('username');
$data['result'] = $this->HomeModel->get_employee($case_id);
$this->load->view('case/user',$data);
//print_r($data);
//die;
}
Here is my model (HomeModel.php)
public function get_employee($case_id)
{
$this->session->userdata('username');
$this->db->select('case_main.case_id,
case_main.case_name,
case_main.firm_name,
case_overview.case_description,
case_priority.priority,
service_delivery_dates.received_date,
service_delivery_dates.expected_delivery_date,
service_delivery_dates.service_status');
$this->db->from('case_tracker.case_assignment');
$this->db->join('case_tracker.case_main', 'case_tracker.case_assignment.case_id=case_tracker.case_main.case_id');
$this->db->join('case_tracker.case_overview', 'case_tracker.case_main.case_id = case_tracker.case_overview.case_id','left');
$this->db->join('case_tracker.case_priority', 'case_tracker.case_overview.case_id = case_tracker.case_priority.case_id' , 'left');
$this->db->join('case_tracker.service_delivery_dates', 'case_tracker.case_priority.case_id = case_tracker.service_delivery_dates.case_id' , 'left');
$this->db->where('case_assignment_case_id', $case_id);
$data = $this->db->get();
return $data->result();
}
Note:- Here case_main, case_overview, case_priority, service_delivery_dates are the different tables in databases and case_tracker is my schema name.
I dont know what to write in controller to fetch the case_id that the admin assigns and when user logs in he/she should be able to see all the data o the particular case_id
Expected result:-
Admin page: https://prnt.sc/novscc --> this how the datatable will be displayed for admin.. he will be having all case data. when he assigns case to user. user should receive only that case.
User page: https://prnt.sc/novtnr -> this is how i want user datatable to be displayed when admin assigns a case.
Here is the database case_assigment table screen shot : https://prnt.sc/novtze (here only case_id & username to whom admin wants to assigns will be there).
For each user, I want to only show to them the cases specifically assigned to them to load on their dashboard when admin assigns them. cases that was not assigned to them will not be listed on their dashboard.
if the admin had assigned the case (case_id will be present) to particular username, then, when user logins, he should be able to see that all the data (tables) related to that particular case_id.
Please help me, im new and learning programming language.
Based on your comment I assume that one employee is assigned to one case. Thus:
function get_employee_case() {
$this->db->select('case_id');
$this->db->where('username', $this->session->userdata('username'));
$q = $this->db->get('case_assignment');
if ($q->num_rows() == 1) {
return $q->row()->case_id;
}
return null;
}
Controller:
$case_id = $this->HomeModel->get_employee_case();
if (!is_null($case_id)) {
$data['result'] = $this->HomeModel->get_employee($case_id);
} else {
$data['result'] = null;
}
View:
if (is_null($result)) {
echo 'no case assigned';
} else {
...
}
Thnx #Alex for the help,
Here is the Result which i was looking for:
Controller:
public function index()
{
$data['result'] = $this->HomeModel->get_employee_case();
$this->load->view('case/user');
/*
print_r($data);
die; */
}
Model:
function get_employee_case()
{
$this->db->select('case_assignment.case_id,
case_main.case_name,
case_main.firm_name,
case_overview.case_description,
case_priority.priority,
service_delivery_dates.received_date,
service_delivery_dates.expected_delivery_date,
service_delivery_dates.service_status');
$this->db->from('case_tracker.case_assignment');
$this->db->join('case_tracker.case_main', 'case_tracker.case_assignment.case_id=case_tracker.case_main.case_id', 'left');
$this->db->join('case_tracker.case_overview', 'case_tracker.case_main.case_id=case_tracker.case_overview.case_id', 'left');
$this->db->join('case_tracker.type_of_services', 'case_tracker.case_overview.case_id = case_tracker.type_of_services.case_id', 'left');
$this->db->join('case_tracker.specific_instructions', 'case_tracker.type_of_services.case_id = case_tracker.specific_instructions.case_id' , 'left');
$this->db->join('case_tracker.case_priority', 'case_tracker.specific_instructions.case_id = case_tracker.case_priority.case_id' , 'left');
$this->db->join('case_tracker.service_delivery_dates', 'case_tracker.case_priority.case_id = case_tracker.service_delivery_dates.case_id' , 'left');
$this->db->where('case_assignment.username', $this->session->userdata('username'));
$query = $this->db->get();
return $query->result();
}
You have to first select the all caes assigned to user
select * from cases where user_id=2
fetch all cases in loop
and then fetch data for each case

How to save html values to MySQL using ajax?

I'm trying to make an HTML table dynamically. I'm just testing with sample, but It's not working as well as I expected. So, I'm asking this question. Let me show you this simple table, it is MySQL database. and I create HTML table.
What I want to do is when I click some node, like a '250', this number will be editable. Edited data will be saved to the MySQL database. So I use the contenteditable="true" attribute value, and when this node loses focus, run some JavaScript function that new data will be saved.
But... It's not working well. Honestly I don't know what the problem is exactly. Google chrome spit up "Uncaught Syntax Error, Unexpected token } ", But I couldn't find what the actual problem is. I'm newbie on this... Could you some guys help me?
sample.html
<body>
<?php
require_once("db_connect.php");
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
?>
<table border="1" style="border-collapse:collapse;">
<thead>
<tr><th>name</th><th>price</th></tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
echo
"<tr>
<td contenteditable='true' onBlur='saveToDatabase(this,'name','$id')'>{$row['name']}</td>
<td contenteditable='true' onBlur='saveToDatabase(this,'price','$id')'>{$row['price']}</td>
</tr>\n";
}
?>
</tbody>
</table>
<script>
function saveToDatabase(editableObj, column, id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
</body>
</html>
saveedit.php
<?php
require_once("db_connect.php");
$result = mysql_query("UPDATE test SET ". $_POST["column"]. " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);
?>
You made it contenteditable but PHP needs an parameter. For example
<input type="text" name="parameter">
will send as $_POST['parameter'] but in your code <td> elements don't have a name. So PHP doesn't know if there is a parameter or what name is.
Maybe you can write your own editable function in Javascript like this:
function doTextArea(i) {
document.getElementById(i).innerHTML="<input type='text' name='table_value'>ssss.";
}
and your php loop can be like this ( I assume it is for loop):
for ($i = 1; $i <= 10; $i++) {
echo
"<tr>
<td><p id=$i ondblclick='doTextArea($i)'> sadasdasdasd</p></td>
</tr>\n";
}

How to auto fill a form with data from database based on drop menu selection

I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.

Display a page after an ajax request

I need a web page where users can modify a data already captured in database. So I made a tab with the list of every data and when a user click on one, I want to redirect the user in a page with matching data.
So this is my tab :
<?php
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_essai, nom_local_essai, thematique FROM public.essai";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
echo'<table class="table table-hover" border="1">';
echo'<thead><tr><th>id_essai</th><th>Nom local</th><th>Thématique</th></tr></thead>';
while ($data = pg_fetch_array($res))
{
echo' <tbody>
<tr>
<td><a id="'.$data['id_essai'].'">
'.$data['id_essai'].'
</a></td>
<td>
'.$data['nom_local_essai'].'
</td>
<td>
'.$data['thematique'].'
</td>
</tr>
</tbody>
';
}
echo'</table>';
?>
And I get the ID of the data selected like this :
<script>
$(document).ready(function(){
$('a').click(function(){
var id_essai = $(this).attr('id');
$.post('traitement_modif_essai.php',{id_essai:id_essai});
});
});
</script>
Now, on the other file, I want to get the ID and display the right page, but I can't get thought.
<?php
session_start();
$_SESSION['id_essai'] = $_POST['id_essai'];
echo $_SESSION['id_essai'];
header('Location:essai_modif.php');
?>
You can redirect the user after the session has been set by you in the PHP in the javascript callback of post
<script>
$(document).ready(function(){
$('a').click(function(){
var id_essai = $(this).attr('id');
$.post('traitement_modif_essai.php',{id_essai:id_essai}, function(){
window.location = "./essai_modif.php";
});
});
});
</script>
and in the PHP
<?php
session_start();
$_SESSION['id_essai'] = $_POST['id_essai'];
echo $_SESSION['id_essai'];
?>

Auto refresh/load data only if new data inserted or updated

In my case, I make auto refresh after X seconds. But I want to make it only refresh when new data inserted or updated.
Here is my script.
refresh.php
<script src="jquery-1.4.js"></script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("refreshnow.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('refreshnow.php?randval='+ Math.random());
}, 1000);
});
</script>
<div id="responsecontainer"></div>
refreshnow.php
<?php
$query = mysqli_query($connection,"select * from `table`");
$rows = mysqli_num_rows($query);
?>
<table style="background:#F0F0F0;" border=1 style="border-collapse:collapse">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
<tbody>
<?php
while($result = mysqli_fetch_array($query)){
echo "<tr>";
echo "<td>".$result["name"]."</td>";
echo "<td>".$result["job"]."</td>";
echo "</tr>";
}
?>
</tbody>
So, could it be possible to load new data automatically when new data inserted or updated without refresh after x seconds?
If you want to use your existing code, just add another column in a mysql table (if you got a config or settings table, this would be easyer, if not just ad timestamp for each record you insert) with the value time(), this updates the timestamp in the database each time a row is inserted/modified.
Then just do a query like:
"select timestamp_column from `settings_table` order by timestamp_column limimt 1"
If ($result["timestamp_column"]+1000>=time()){
//do the refreshnow.php code here
}
Hope it helps,
Cheers

Categories

Resources