Make a dialog box in my HTML page by some conditions - javascript

What I need to do.... In php-part of my login.php I check the user password and login this way:
<?php
// some code
session_start();
$query = "SELECT * FROM CRM.Users WHERE Login = '$l_username' AND Password = '$l_password'";
$result = mysql_query($query) or die ( "Error : ".mysql_error() );
while($row = mysql_fetch_assoc($result)){
...
if(mysql_num_rows($result) < 1){
// echo The password or login is wrong
</php>
In My HTML i have:
<div id="dialog" title="Basic dialog">
<p>The password or login is wrong</p>
</div>
And in my JS part I have:
function myfunction()
{
$( function() {
$( "#dialog" ).dialog();
} );
}
But when I bind MyFunction() with some test submit button (by onClick event) I see the DIV part in my page like common html text. But I dont want to see it while the condition wont true. So, My questions:
How I can realize the password/login check, throwing dialog box and when User click OK, i want to pull out user to index.php page
How I can hide the DIV for Dialog while condition is false

Here is the code for your problem:
<?php
if(mysql_num_rows($result) < 1) {
?>
<script>
$(function(){
myFunction();
});
</script>
<?php }?>
<script>
function myfunction()
{
$("#dialog").dialog({
resizable: false,
modal: true,
buttons: {
OK: function() {
$( this ).dialog( "close" );
window.location = 'http://localhost';
}
}
});
}
</script>

Your code is fine. It just needs some cleaning up:
<?php
if (!isset($_SESSION)) {
session_start();
}
$query = "SELECT *
FROM CRM.Users
WHERE Login = '".mysql_real_escape_string($l_username)."'
AND Password = '".mysql_real_escape_string($l_password)."'
LIMIT 1";
$resource = mysql_query($query) or die ("Error : ".mysql_error() );
// If there is one result, the login is successfull
if (mysql_num_rows($result) == 1) {
$record = mysql_fetch_assoc($resource);
$_SESSION['user'] = array(
'id' => $record['id'],
'username' => $record['Username'];
);
// Redirect
header("Location: secure.php");
exit;
}
?>
To check if a user is logged in:
if (!isset($_SESSION['user'])) {
header("Location: login.php");
exit;
}
Note: Others will probably complain about mysql_* functions not being secure. and they are right. These functions are deprecated. Instead I recommend using mysqli_*
Update
I forgot the part where the question was about hehe. Adding a dialog can be done very easily.
<script type="text/javascript">
if(!confirm("...")) return;
// redirect here
</script>

Related

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.

From php to JavaScript - run function and to php again

I have a problem with some PHP / JavaScript. I know a bit PHP but new to Javascript.
I'm trying to get the JavaScript alertify to work with php.
My Q's:
1: How can I parse a PHP variable to a Javascript alertify function
2: It need to be a if php statement, because
if ($id==1){*show alertify};
elseif($id==2){*Do nothing*};
3: And when back to PHP again.
4: What function do I need to call to get the alertify on page load?
The logic:
Please examples in JavaScript because i'm totally new :)
My code so far:
<?php include_once "config.php";
if(!isset($_SESSION['idUserType'])){
$sql = mysql_query("SELECT * FROM Test WHERE id = $id");
while($row = mysql_fetch_array($sql )){
$idStatus = $row["idStatus"];
if($idStatus==1){
echo '<BODY onLoad="confirm()">';
echo '<script>window.onload = confirm();</script>';
;}
elseif($idStatus==2){
$sqlsearchoutput .= 'Do nothing'
;}
}}?>
JavaScript code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="jscss/alertify.min.js"></script>
<script>
function reset () {
$("#toggleCSS").attr("href", "jscss/alertify.default.css");
alertify.set({
labels : {
ok : "ok",
cancel : "cancel"
},
delay : 5000,
buttonReverse : false,
buttonFocus : "ok"
});
}
// Standard Dialogs
$("#confirm").on( 'click', function () {
reset();
alertify.confirm("Comfirm", function (e) {
if (e) {
alertify.success("You clicked: Cancel");
} else {
alertify.error("You clicked: OK");
}
});
return false;
});
</script>
I think your problem is that the "JavaScript" is inserted into the document after the php echos:
if($idStatus==1){
echo '<BODY onLoad="confirm()">';
echo '<script>window.onload = confirm();</script>';
;}
You will need to have them both inserted at the same time.

Javascript popup after php / mysql database update

What I have is php that updates the database field after a client signs a form. This works, but I want it to redirect to a new page after it is confirmed that the user signed it by clicking OK. It they click CANCEL it will leave them on the same page.
<?php
$username = 'joeblow';
require_once ("/mypath/include/connnect_db.php");
?>
<p>Please only submit this after above form is completely signed.</p>
<form id="item_complete" method="post">
<input name="submit" type="submit" form="item_complete" value="Submit After Signing">
</form>
<?php
if(isset($_POST['submit'])) { //if the submit button is clicked
$complete = 'c';
$query = "UPDATE mytbale SET mycolumn='c' WHERE username='$username'";
mysqli_query($con,$query) or die("Cannot Update");
echo "<script> confirmFunction(); </script>";
}
require_once ("/mypath/include/disconnect_db.php");
?>
<script type="text/x-javascript">
function confirmFunction(){
var r=confirm("Confirm that you have signed the form!");
if (r==true){
window.open("http://smartpathrealty.com/smart-path-member-page/");
}
else {
}
}
</script>
My problem is the javascript function does not execute after the php updtates the database.
I appreciate any advice or comments you have about this.
The problem is that you are using separate <script> tags and calling the function before it is defined. These two together do not work well. Also, I'm pretty sure that <script type="text/x-javascript"> does not work anyway since it's outdated and that you want <script type="text/javascript">
You can do the following:
Move function up and fix x-javascript:
<?php
$username = 'joeblow';
require_once ("/mypath/include/connnect_db.php");
?>
<p>Please only submit this after above form is completely signed.</p>
<form id="item_complete" method="post">
<input name="submit" type="submit" form="item_complete" value="Submit After Signing">
</form>
<script type="text/javascript">
function confirmFunction(){
var r=confirm("Confirm that you have signed the form!");
if (r==true){
window.open("http://smartpathrealty.com/smart-path-member-page/");
}
else {
}
}
</script>
<?php
if(isset($_POST['submit'])) { //if the submit button is clicked
$complete = 'c';
$query = "UPDATE mytbale SET mycolumn='c' WHERE username='$username'";
mysqli_query($con,$query) or die("Cannot Update");
echo "<script> confirmFunction(); </script>";
}
require_once ("/mypath/include/disconnect_db.php");
?>
Fiddle: Fiddle
You could post the form via ajax and in your php you can return a response to the javascript. That was you could use a callback to fire the new window.
Heres a jquery example:
$.post('/myscript.php', {foo: 'bar'}).done(function (response) {
window.open(......);
});
I believe you are using same page for landing and updating. What you need is to update your echo to add an onload.
echo "<script> window.onload=confirmFunction(); </script>";
Hope this what you are looking for.
<script type="text/javascript">
function confirmFunction(){
var r=confirm("Confirm that you have signed the form!");
if (r==true){
window.open("http://smartpathrealty.com/smart-path-member-page/");
}
else {
}
}
</script>
<?php
if(isset($_POST['submit'])) { //if the submit button is clicked
$complete = 'c';
$query = "UPDATE mytbale SET mycolumn='c' WHERE username='$username'";
mysqli_query($con,$query) or die("Cannot Update");
echo "<script> confirmFunction(); </script>";
}
require_once ("/mypath/include/disconnect_db.php");
?>
<script type="text/javascript">
window.onload = function(){
<?php
if(submitted){
echo "confirmFunction();";
}
?>
}
</script>
Try:
if (r==true) {
window.open("http://smartpathrealty.com/smart-path-member-page/");
}
else {
window.location = "PAGE THAT YOU WANT";
}

PHP / Ajax : How to show/hide DIV on $_SESSION variable value?

I have searched many, many topics on the Net discussing about session variables and how to get them from Javacript through Ajax. However, though I have been able to do so, this doesn't completely solve my problem.
Objective
To provide online inventory management online.
Constraints
Only authenticated users can manage the online inventory
Inventory management controls are hidden from an unauthenticated user
Each sections must be independently informed of the authentication in order to show/hide their controls accordingly
Code Samples
authenticate.php
project.js
index.php
atv.php
atv-inventory-list.php
sectionhandler.php
index.php
<?php session_start(); ?>
<html>
...
<div id="newAtvDialog" title="Input information on the new ATV">
<form id="newAtvAjaxForm" action="addNewAtv.php" method="post">
...
</form>
</div>
<div id="section">
<$php echo file_get_contents("inventory-sections.html"); ?>
</div>
...
</html>
authenticate.php
<?php
require_once "data/data_access.php";
$userName = "";
$password = "";
if (isset($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isset($_REQUEST["password"])) $password = $_REQUEST["password"];
$isAuthentic = isAuthenticUser($userName, $password);
$_SESSION["isAuthentic"] = $isAuthentic;
echo $isAuthentic;
// I try to use the below-written function where ever I need to show/hide elements.
function isCurrentUserAuthenticated() {
return isset($_SESSION["isAuthentic"]) && $_SESSION["isAuthentic"];
}
?>
project.js
$(document).ready(function() {
$("#newAtvDialog").dialog({
autoOpen: false,
closeOnEscape: true,
modal: true,
width: 1000
});
$("#newAtvAjaxForm").ajaxForm(function(data) {
$("#newAtvDialog").dialog("close");
$("#section").load("sectionhandler.php?section=atv&type=-1&make=0&year=0&category=0", function(event) { $("button").button(); });
});
});
atv.php
<div id="newAtvButton"> <!-- This DIV is to be hidden when not authenticated -->
<button id="addNewAtvButton">Add New ATV</div>
</div>
<div id="criterion">
...
</div>
<div id="atv-inventory">
<?php include ('atv-inventory-list.php'); ?>
</div>
atv-inventory-list.php
<?php
$type = -1;
$make = 0;
$year = 0;
$category = 0;
if (isset($_REQUEST["type"])) $type = $_REQUEST["type"];
...
$atvs = getAllAtvs($type, $make, $year, $category);
foreach ($atvs as $value=>$atv):
?>
<div class="inventory-item">
<img src="<?php echo utf8_decode($atv->getPathToImage())">
<div class="item-title">
...
</div>
<div id="commands">
<!-- This is the way I have tried so far, and it doesn't seem to work properly. -->
<button id="removeAtvButton"
class="<?php echo isCurrentUserAuthenticated() ? 'show' : 'hide'; ?>">
Remove ATV
</button>
</div>
</div>
sectionhandler.php
$section = "";
if (isset($_REQUEST["section"])) $section = $_REQUEST["section"];
$type = -1;
$make = 0;
$year = 0;
$category = 0;
// getting values from $_REQUEST[]
$activatedSection = "";
switch($section) {
case "atv": $activatedSection = "atv.php";
...
}
$file = $url.raw_url_encore($activatedSection);
include $file;
Supplementary thoughts
I thought of setting a boolean session variable which would expire after about 20 minutes of inactivity from the user, forcing him to log in again.
I know I shan't use passwords stored in the database. This is the first step of the authentication within this site which I shall put online pretty soon, as the client is going to ask for delivery any time soon. Encrypted passwords will be the next step. But first, I need the show/hide feature to work properly.
I have also thought about cookies, and being quite new to web development, I ain't quite sure what would be the best approach. As far as I'm concerned, the simplest the best, as long as it implies a minimum of security. This is not the NASA site after all! ;-)
Thanks everyone for your inputs! =)
It's an idea, but you can work on/from it;
actionURL is a php file where you can check if the user is logged in with a valid session.
ajaxSession function returns true or false if the user is logged.
Then you can call this function every X seconds/minutes to control if the session still going.
window.setInterval(function(){
// call your function here
if(ajaxSession(actionUrl)){
//return true, user logged, append/show protected divs.
}else{
//return false, remove/hide protected divs and ask user to log.
}
}, 5000); //every 5 seconds.
ajaxSession function:
function ajaxSession(actionUrl) {
var sessionOK= false;
$.ajax({
async: false,
url: actionUrl,
success: function(msg) {
// check the return call from the php file.
if(msg== 'OK'){
sessionOK = true;
}else{
sessionOk = false;
}
}});
return sessionOK;
}
EDIT
I will add an example code for the actionUrl, that will return if the session is isset or not to the ajaxSession function:
<?php
session_start();
// $_SESSION['reg'] is true when the user is logged in.
if($_SESSION['reg'] == true){
echo 'OK';
}else{
echo 'NO';
}
?>
Remember to check in the ajaxSession function the result of the Ajax call. If it's Ok, then sessionOk = true, if not, sessionOk = false.

There is no alert when submitting a form using ajaxForm plugin

How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){

Categories

Resources