Sql Php Ajax - Check if change in database - javascript

I currently have a ajax script to run a notiload.php file which runs every 5 seconds to check if theres a change in the database, if theres a change it then outputs "1 New" for a message. However as I will be introducing a notification sound in that file. It will chime every 5 secconds when the file is loaded. Of course this will piss people off. So I need the script to check if theres a change in the database. I have a time and date stamp of every message, with the message being viewed as 2 and not as 1. So if theres a change in the database I will need it to call that file or play a sound.
here is my ajax script inside the main page
<script type="text/javascript">
$(document).ready(function(){
refreshTable<?= $FriendName->id ?>();
});
function refreshTable<?= $FriendName->id ?>(){
$('#NotiLoad<?=$FriendName->id?>').load('elements/notiload.php?id=<?=$FriendName->id?>', function(){
setTimeout(refreshTable<?= $FriendName->id ?>, 5000);
});
}
</script>
<div id="NotiLoad<?= $FriendName->id ?>" style="display: inline-block;"></div>
And here is the php of notiload.php
<?php
session_start();
// redirect to index page if not superuser
$con = mysqli_connect('localhost','root','','');
if (!$con) {
die('Could not connect to Socialnetwk DB: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
?>
<?php
$uid = $_GET['id'];
$mid = $_SESSION['user']['id'];
?>
<?php $usrload = $con->query("SELECT * FROM message WHERE sender = $uid AND recipient = $mid AND seen = '2' OR sender = $mid AND recipient = $uid AND seen = '2'"); ?>
<?php while($FriendName = $usrload->fetch_object()): ?>
<h6 style="display:inline-block;font-size: 10px;color:#37BC9B">1 New</h6>
<?php endwhile;?>

Related

How can I get data from MySQL for each user

I need help. I crated a MySQL database and I connected database with login and registration form. All it´s working. I tried to create page that show all data about user from database. I created tried this code:
<p>Username: <?php echo $_SESSION['username']; ?></p>
<p>Email: <?php echo $_SESSION['email']; ?></p>
<p>Create profile date and time: <?php echo $_SESSION['create_datetime']; ?></p>
But that showed me only username.
I created this from this page.
Can you help me with this? Very much thanks for response!
Inside login.php page you need to assign email and create_datetime to $_SESSION. It should be like
if ($rows == 1) {
while($row = $result->fetch_assoc()) {
$_SESSION['username'] = $row["username"];
$_SESSION['email'] = $row["email"];
$_SESSION['create_datetime'] = $row["create_datetime"];
}
// Redirect to user dashboard page
header("Location: dashboard.php");
}

Header not working in php

I have a program that brings an image from the database and displays it inside an image div in my website. The below code was working successfully on my local wamp server but when I moved it to an online server it did not work anymore.
<?php
session_start();
include 'dbConnector.php';
$uID = $_SESSION['loggedUserID'];
$sql = "SELECT photo FROM hostmeuser WHERE userID = '$uID'";
$result = $conn->query($sql);
if(!$row = mysqli_fetch_assoc($result))
{
$imgData = "Assets/man.jpg";
}
else
{
$imgData = $row['photo'];
}
header("content-type: image/jpg");
echo $imgData;
?>
I have noticed that all (header) functions are not working on the new server and I have no control over this server so I replaced every:
header("Location: example.php")
with:
?>
<script type="text/javascript">
window.location.replace("example.php");
</script>
<?php
it is working fine now on most cases but not this one!
header("content-type: image/jpg");
Can you suggest any solution for this? or at least do you know how to represent this command in javascript?

How to auto-save and auto-update textarea

I'm currently attempting to create a test-website based on the "Secret Diary" project of a web developer course. I'm trying to create a page that saves all of the notes written into a textbox, and displays them when I log in again. Almost everything works - I can start a session and display the saved text when I log in, but the box is deleting the textbox's saved data when the page is loaded. I know that there are better ways of storing the info, I'm just looking for how to get this method to work. This should be all of the relevant code:
mainpage.php:
<?php include("updatediary.php"); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form method="post">
<textarea class="form-control"><?php echo $diary; ?></textarea>
</form>
<script>
$("textarea").keyup(function() {
$.post("updatediary.php", function(){diaryInput:($("textarea").val());} );
});
</script>
updatediary.php:
<?php
include("connection.php");
$query = "SELECT content FROM users WHERE id='".$_SESSION['id']."' LIMIT 1";
$result = mysqli_query($dbCon,$query);
$row = mysqli_fetch_array($result);
$diary = $row['content'];
if ($_POST['diaryInput']!="") {
$updateQuery = "UPDATE `users` SET `content`='".mysqli_real_escape_string($dbCon, $_POST['diaryInput'])."' WHERE id='".$_SESSION['id']."' LIMIT 1";
if (mysqli_query($dbCon, $updateQuery)) {
echo "saved";
} else {
echo "not saved";
};
}
?>
connection.php:
$dbCon = mysqli_connect("localhost", "owenxwfg_admin", "(password)", "owenxwfg_users");
Any help would be awesome. I personally think that there's a problem with my $.post part.

Ensure that each user's click only is sent once in a defined time period

Hi I have the following code which I am trying to adapt to make sure that when Like is clicked by a user who is logged in, then only one request is sent in a predetermined period of time that can be adjusted i.e Like can be clicked and a request sent only once every 5 minutes. There must be a javascript function I can use but I can't figure it out.
index.php:
<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>
<html>
<body>
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(', $userid,');">Like</a>';
?>
<script type ="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type ="text/javascript" src="like.js"></script>
</body>
</html>
connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
init.php:
<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>
like.js:
function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
} else {
alert(data);
}
});
}
like.php:
<?php
function add_like($userid) {
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?
like_add.php
<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>
If you pass the a tag into like_add like so:
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(this, '.$userid.');">Like</a>';
?>
You can disable it in the javascript function for a set time period:
function like_add(a, userid) {
a.disabled = true;
setTimeout(function(){
a.disabled = false;
), 5000});//Code will execute in 5 seconds to enable the a tag
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
}else{
alert(data);
}
});
}
Is this something alogn the lines of what you were looking for?
In a completly not recommended way, you could define
var isLikeable = true;
function likeStatus(secs) {
isLikeable = false;
window.setTimeout("isLikeable = true;", (secs*60));
}
then, when clicking the "like" you would check
if (isLikeable) { // do like and call likeStatus(300); }
Do you need this to be enforced on the back-end, or is disabling it through the UI sufficient? You could theoretically get people hacking it using Developer tools or Firebug, but this seems very unlikely from casual users.
On the front end, I would user jQuery to add code on the click event that disables the "Like" button with a timeout, like this:
// First, move your click handler to your script file
$('.like').click( function(event) {
// Make sure clicking the button doesn't submit any form context that might be present
event.preventDefault();
var DURATION_IN_MINUTES = 5;
// Grab the user id that will be added as an attribute of your element: data-user-id="$userid"
var user_id = $(this).data('userID');
// Run your function
like_add(user_id);
// Disable clicking like (it's easiest to do this with a button, by far
$(this).prop({'disabled':true,'title':'Disabled for ' + DURATION_IN_MINUTES + ' minutes');
// Set a timer to re-enable the like button in 5 minutes
setTimeout( function() { $(this).prop({'disabled':false,'title':''}), DURATION_IN_MINUTES * 60 * 1000}
});
and then in your HTML:
echo '<a class="like" href="#" onclick="like_add(', $userid, ');">Like</a>';
becomes
echo '<button class="like" data-user-id="' + $userid + '">Like</button>';
I don't have a PHP environment to test this (and I haven't tested the JavaScript itself, to be honest), but this should be enough to get you started.
If you want to block multiple submissions on the back-end, you'll want to timestamp your likes, and do a look-up to see the last time a given user "liked" that link.

how to make the result appear in popup widow?

I want to make the result comes out in a popup window.
Code:
<?php
$con=mysqli_connect("localhost","root","1234","fyp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT password FROM admin WHERE email = '$_POST[email]' AND Admin = '$_POST[admin]'");
while($row = mysqli_fetch_array($result))
echo "your password is : " . " $row['password']" ;
mysqli_close($con);
?>
Is it possible to make it echoed in popup window like javascript alert messages ??
I have tried this but still not working
echo "<script> alert ("<?php echo 'your password is: ' . '$row['password']'?>")</script>";
I found a maybe strange solution for this a while back.
echo "<style onload=\"jsfunc($row['password']);\"></style>";
//in your html or javascript add this function
<script type='text/javascript'>
function jsfunc(data){
alert(data);
}
</script>
the style tag is invisible and will run the function onload, so when its gets echoed. Also I use the style tag because its one of the few tags where the onload works when you echo it like this.
Its a strange solution but it works.
There are some serious flaws in your code, including it being open to SQL Injection. I'd recommend changing it to look more like this:
$con = new MySQLi("localhost","root","1234","fyp");
if($con->connect_errorno) {
echo "Failed to connect to MySQL: ".$sql->connect_error;
}
$email = $sql->real_escape_string($_POST['email']);
$admin = $sql->real_escape_string($_POST['admin']);
$query = "SELECT password FROM admin WHERE email = '$email' AND Admin = '$admin'";
$result = $sql->query($query);
if($result) {
$row = mysqli_fetch_assoc($result);
$pass = $row['password'];
echo '<script> alert("Your password is '.$pass.'");</script>';
} else {
//do some error handling
}
//the closing of a mysqli connection is not required but
mysqli_close($con);
Real escape string is not 100% proof against injection but is a good place to start with sanitising your inputs. Additionally I would strongly advise against storing your passwords in plain text. Please take a look at the PHP sha1() function or the SQL equivalent when storing the passwords initially.
Use this code
<?php
$alert='your password is: '.$row['password'];
?>
<script>
alert("<?php echo $alert; ?>");
</script>
It will work for sure.

Categories

Resources