how to open html page using trigger - php

i am using database trigger
when database row updated i want to get real time notification like change happened now
suppose i am using message table in my database
suppose user inserted value in message table. i want change should be noted using
trigger at real time and then i want open an html page when row inserted in my
message table then html page should open or an alert box show notification
that"you received a new message".
Please help me to solve this problem
for example
CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DB AutoMailer',
#recipients = 'user#example.com',
#body = 'The DB has changed',
#subject = 'DB Change';
in above example mail is sending but i want to open html page i need syntax to open html page

Well below is a example of what you need exactly:
javascript
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "file.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
then php
$sql = "SELECT count(*) as count FROM i_case";
$qry = pg_query($connection, $sql);
$row = pg_fetch_assoc($qry);
echo $row['count'];

Related

How to handle AJAX error if sql update fails?

I have a php file, which updates the SQL, if the "follow this user" button is clicked, and an AJAX calls this PHP file. The code below works, it follows the user! My problem is: If, for some reason the SQL update fails, I want the AJAX to drop an error message (e.g. an alert), but I really don't know how this could be possible. The AJAX doesn't know whether the update succeeded or not.
Here's my code:
PHP
if(!empty($_GET['a']) and $_GET['a']=='follow')
{
$id = sql_escape($conn,$_GET['id']);
$me = $user2[0];
//the user's id who clicks on the follow button
$query = sql_fetch(sql_query($conn, "select * FROM
forum where id='$id'"));
//check who created this forum, so we know who to follow
$follow_this_user = $query['user'];
//the user to follow
$now = date('Y-m-d H:i:s');
$already_follow_user = sql_fetch(sql_query($conn,
"SELECT * FROM follow WHERE user_id=".$me." AND
followed_user =".$follow_this_user." "));
//check if user already followed by this user
if(empty($already_follow_user[0])) {
//if not followed
sql_query($conn,"INSERT INTO follow
(user_id, followed_user, date) VALUES
('".$me."', '".$follow_this_user."', '".$now."');")
or die(mysqli_error($conn));
}
}
AJAX:
$(document.body).on('click', '.followable', function(){
//User clicks on the follow text, which has "followable" class
$.ajax({
//type: 'GET',
url : '/ajax/ajax_follow.php?a=follow&id=<?php print $topic[id]; ?>'
//the $topic['id'] is the id of the current topic, which
//I need to know who created this forum, to follow that user
//(as mentioned above in the php code)
});
I need data and error, but no idea how to get them working. I tried many things, but I just can't get the data.
Add this to your ajax request:
success: function(data) {
alert(data);
}
And simply echo something on your PHP page.
For example:
$result = mysql_query($sql);
echo $result;
If you want to recieve more data, JSON is your friend.

how to add a content to html from a database after inserting data from mysql no refresh php

For example I am a user and I want to post a comment and after submitting it and saved to my database. The other page of the admin updates and automatically the data that I inserted displays without refreshing the page of the admin. Help please..
any code can help. Thanks. I'm using php for server-side language. Any language can help javascript or ajax.
Javascript (jQuery):
$.post('path_to_your_php_script.php', function(data) {
$('the_dom_element_you_want_to_show_the_comment_in').html(data);
});
Somewhere in path_to_your_php_script.php:
// some code to save the data
echo '<div>New comment</div>';
exit;
For more information, please refer to jQuery's post and ajax methods. You can do the same thing without jQuery, but you shouldn't reinvent the wheel.
yourphpfile.php is the php file where you need to do all your database operations (in your case its insert into database).
So,basically you want to show the recently insert data in a webpage without refreshing the page, to do that, we need Ajax.
So, do your insert operation in yourphpfile.php, and if the insert operation is successful, just return the result (inserted data into DB) using echo $output;exit;
where $output = 'recently inserted data';
That's what you need to do in the php side.
Your yourphpfile.php:
<?php
//your database insert operation
echo $output;// $output should have the inserted data
exit;
?>
Now in ajax function:
You could use jquery.ajax
$.ajax({
type: "GET",
url: "yourphpfile.php",
success: function(response){
if(response != '') {
//data that I inserted displays without refreshing the page of the admin
$('yourDivContent').html(response);
} else {
// response error
}
}
});
In the reponse variable you would get what you have echoed in the yourphpfile.php.
That is $output. Then you could use the reponse varible inside ajax function and use it to insert into your HTML.
Suppose you have a form and you can use Ajax for sending the data to the backend. The ajax call would look in the following way:
var id = $(this).attr('id');
$.ajax({
type:"POST",
url:"ajax.php",
data:{id:id},
success:function(data){
// do something if insertion into database has succeeded
}
});
...and in php you write something as:
// Connecting to Database
mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die ('Can not connect to MySQL database');
// Selecting Database
mysql_select_db(DBNAME) or die ('Cant select Database');
$action = mysql_real_escape_string($_POST['action']);
if ($action == "insert")
{
foreach ($recordArray as $key=>$value) {
$query = "INSERT INTO `TABLE`
SET name = `".$_POST['name']."`
SET age = `".$_POST['age']."`
.
.
mysql_query($query) or die('Error, insert query failed');
}

how to get the current added in the table without getting all the data

guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead

Display Notifications

I'm trying to follow the first answer here in order to accomplish my alert feature on my app. Facebook like notifications tracking (DB Design)
but in that example, the user has to open the notifications page to check for new notifications. For me, i need to let user knows that there is a notification (database updated) by displaying an icon like Facebook alerts or something like that.
is there any clear idea about how to do that ?
EDIT
i did something but can't test it coz i don't have my laptop right now.
would you please take a look and let me know if something not OK ?
PHP file
$userID=$_GET["userid"];
//Database connection
$sql = 'SELECT count(*) as count FROM list_notifications WHERE userid ='.$userID;
$qry = pg_query($sql);
$row = pg_fetch_array($qry);
echo $row['count'];
jQuery & JavaScript
var old_count = -1;
setInterval(function() {
$.get("file.php", { userid: "userid" },
function(data){
if (data > old_count) {
alert("the list is updated with: " + data);
//OR
//console.log('the list is updated with:' + data);
old_count = data;
}
}
)},5000); // every 5 seconds
once the user is logged in, the userid must be sent periodically to the php file to check for new notifications. then display them to the user.
for count variable, i made it Increases incrementally with Database trigger.

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

Categories