Create a simple booking system using Jquery UI datepicker - javascript

I'm building a simple booking system for a friend's holiday house and I'm really struggling to implement it. Only one group can stay in the cottage at one time. First let me run through what the booking system must be able to do (things I've already completed are in brackets).
Receive emails from guests with the dates they want to stay
(completed but haven't included as not relevant).
Admin can then choose those dates in Jquery UI datepicker and
store the fromDate and toDate in the database (completed but not
sure if correct).
The fromDate and toDate are then retrieved from the database and then
disabled in the Jquery UI datepicker (Don't know how to do this).
When the fromDate and toDate are disabled all the dates in between
those dates should be disabled, with the fromDate and toDate in a
slightly different colour to indicate the check in and check out
times (No idea how to do this).
The admin should be able to edit and delete dates stored in the
database. No need for taking payment as this will be handled
offline.
Ok, I'm going to paste in all the code that I have completed so far. I used includes in my file but I will post each file separately here in the order they appear. The most important ones, where all the action is happening are calendar.php and datepicker-admin.js but I've posted everything for context. I really am gazzumped here so if someone could walk me through a solution and help me understand what's going on I would really appreciate it. I took on this project because I thought it would be a good way to learn PHP but I'm a little over my head.
config.php
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "calendar");
define("DB_PORT", "XXXX"); // Not going to display my port online
define("DB_USER", "db_user");
define("DB_PASS", "db_password");
database.php
<?php
require('config.php');
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";port=" . DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Could not connect to the database";
exit;
}
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<title>Sticky Footer Navbar Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/sticky-footer-navbar.css" rel="stylesheet">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Wrap all page content here -->
<div id="wrap">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Muscheltraum</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li class="dropdown">
Dropdown <b class="caret"></b>
<ul class="dropdown-menu">
<li>Action</li>
<li>Another action</li>
<li>Something else here</li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li>Separated link</li>
<li>One more separated link</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--container-->
</div><!--navbar-->
calendar.php
<?php
require('inc/header.php');
require('database.php');
// a request method of post indicates that
// we are receiving a form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fromDate = trim($_POST["fromDate"]);
$toDate = trim($_POST["toDate"]);
if ($fromDate == "") {
$error_message = "You must select a from date";
}
if ($toDate == "") {
$error_message = "You must select a to date";
}
else {
try {
$results = $db->prepare("INSERT INTO availability (fromDate, toDate) VALUES (?, ?)");
$results->bindParam(1, $fromDate);
$results->bindParam(2, $toDate);
$results->execute();
} catch (Exception $e) {
echo "Data could not be inserted.";
exit;
}
header("Location: " . "calendar.php/?status=thanks");
}
}
try {
$results = $db->prepare("SELECT fromDate, toDate FROM availability");
$results->execute();
} catch (Exception $e) {
echo "Data could not be retrieved.";
exit;
}
$disablethese = $results->fetch(PDO::FETCH_ASSOC);
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
<p class="alert alert-success">Successful!</p>
<?php } else { ?>
<?php
if (isset($error_message)) {
echo '<p class="alert alert-danger">' . $error_message . '</p>';
}
} ?>
<form action="calendar.php" method="post">
<div class="form-group">
<label for="fromDate">From</label>
<input type="text" id="fromDate" name="fromDate" data-disablethese="<?=json_encode($disablethese)?>">
<?php echo '<pre>';
var_dump($disablethese);
?>
</div>
<div class="form-group">
<label for="toDate">To</label>
<input type="text" id="toDate" name="toDate"></input>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
<?php require('inc/footer.php');?>
footer.php
</div><!--endwrap-->
<div id="footer">
<div class="container">
<p class="text-muted credit">Place sticky footer content here.</p>
</div>
</div>
<!-- Bootstrap core Javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-ui-1.10.4.custom.min.js"></script>
<script src="js/jquery.ui.datepicker-de.js"></script>
<script src="js/datepicker.js"></script>
<script src="js/datepicker-admin.js"></script>
</body>
</html>
datepicker-admin.js
var disablethese = $("#fromDate").data("disablethese");
console.log(disablethese);
$('#fromDate').datepicker({
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [disablethese.indexOf(string) == -1];
}
});
This is what my table looks like at the moment. It only has one row at the moment. id: 10 fromDate: 2014-02-28 toDate: 2014-02-23

Related

PHP dynamic list retrieval returning Undefined index

I've been testing and playing around as part of personal practice, however, I got stuck in the below point where I want to add a list of items via javascript and upon submission, I want to verify and then store the added list. However, once I submit I get an error Unidentified index as if the value is not submitted as checked by isset function and it's always returning empty. After further looking in StackOverflow, I noticed some are referring to the HTML structure; hence, I minimized the HTML to look like the below :
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="assets/vendor/bootstrap/css/bootstrap.min.css">
<link href="assets/vendor/fonts/circular-std/style.css" rel="stylesheet">
<link rel="stylesheet" href="assets/libs/css/customeStyle.css">
<link rel="stylesheet" href="assets/libs/css/style.css">
<link rel="stylesheet" href="assets/vendor/fonts/fontawesome/css/fontawesome-all.css">
<title>Concept - Bootstrap 4 Admin Dashboard Template</title>
</head>
<body>
<!-- ============================================================== -->
<!-- main wrapper -->
<!-- ============================================================== -->
<?php //include("navBar.php"); ?>
<!-- ============================================================== -->
<!-- left sidebar -->
<!-- ============================================================== -->
<?php //include("SlideBar.php"); ?>
<!-- ============================================================== -->
<!-- end left sidebar -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<?php
if(isset($_POST["submit"])){
//$test = $_POST["patName"];
if(isset($_POST["medAdded0"])){
//echo $value;
$listName= $_POST["medAdded0"];
echo '<script language="javascript">';
echo 'alert("'.$listName.'")';
echo '</script>';
echo $listName;
}else {
//echo $value;
echo '<script language="javascript">';
echo 'alert("still empty")';
echo '</script>';
echo $_POST["medAdded0"];
}
}
?>
<form action="#" method="POST">
<div class="row">
<div class="col-xl-8 col-lg-8 col-md-8 col-sm-12 col-12">
<div id="medListContainer" class="form-group">
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<h5 class="card-header">List of Medication</h5>
<div class="card-body">
<div class="list-group" id="pillsList">
<button class="list-group-item list-group-item-action" value="noor">Dapibus ac facilisis in</button>
<button class="list-group-item list-group-item-action" value="btn2">Morbi leo risus</button>
<button class="list-group-item list-group-item-action" value="btn3">Porta ac consectetur ac</button>
</div>
</div>
</div>
</div>
<input class="btn btn-success" type="submit" name="submit" value="Save">
</form>
<!-- Optional JavaScript -->
<!-- jquery 3.3.1 -->
<script src="assets/vendor/jquery/jquery-3.3.1.min.js"></script>
<!-- bootstap bundle js -->
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.js"></script>
<!-- slimscroll js -->
<script src="assets/vendor/slimscroll/jquery.slimscroll.js"></script>
<!-- main js -->
<script src="assets/libs/js/main-js.js"></script>
<script>
var indexCounter=0;
$('#pillsList').on('click', function (e) {
e.preventDefault();
var targetList = document.getElementById("medListContainer");
var medValue= e.target.value;
if (indexCounter==10) {
//code
alert("you've exceeded your limit, please generate new ");
}else{
addMedList(medValue,targetList);
}
});
function addMedList(BtnValue,targetList) {
//function to place the list of selected medicaition
var btn = document.createElement("INPUT");
btn.innerHTML= BtnValue;
btn.className = "list-group-item list-group-item-action";
btn.setAttribute("value", BtnValue);
btn.setAttribute("id", 'medAdded' + indexCounter);
btn.setAttribute("name", 'medAdded' + indexCounter);
indexCounter++;
btn.setAttribute("type", "button");
targetList.appendChild(btn);
}
</script>
</body>
</html>
You've written:
if(isset($_POST["medAdded0"])){
//echo $value;
$listName= $_POST["medAdded0"];
echo '<script language="javascript">';
echo 'alert("'.$listName.'")';
echo '</script>';
echo $listName;
}else {
//echo $value;
echo '<script language="javascript">';
echo 'alert("still empty")';
echo '</script>';
echo $_POST["medAdded0"];
}
The else block is executed when $_POST["medAdded0"] is not set. So it makes no sense to try to echo it there. Get rid of the line
echo $_POST["medAdded0"];

Syntax Error 'SCRIPT1002' using Internet Explorer 11

SCRIPT1002: Syntax error
index.php, line 4 character 37
I got this error in IE11 and my .click() handlers are not working on the page where the error occurs (only in IE11). On lines 1 to 10 I got some standart meta tags so that shouldn't be the problem (I removed them and still received the error).
Because I got a lot of code and I don't know where exactly this error occurs. What's the best way to find the responsible code for this error?
Here is the index.php file referenced in the error:
<!DOCTYPE html>
<html lang="en">
<?php
include("database/connect.php");
include("modul/session/session.php");
$sql = "SELECT * FROM `tb_appinfo`;";
$result = $mysqli->query($sql);
if (isset($result) && $result->num_rows == 1) {
$appinfo = $result->fetch_assoc();
}
$sql = "SELECT * FROM `tb_ind_design` WHERE tb_user_ID = $session_userid;";
$result = $mysqli->query($sql);
if (isset($result) && $result->num_rows == 1) {
$row = $result->fetch_assoc();
}
?>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="<?php echo $appinfo["description"];?>">
<meta name="author" content="A.Person">
<title><?php echo $appinfo["title"];?></title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<?php
if (preg_match("/(Trident\/(\d{2,}|7|8|9)(.*)rv:(\d{2,}))|(MSIE\ (\d{2,}|8|9)(.*)Tablet\ PC)|(Trident\/(\d{2,}|7|8|9))/", $_SERVER["HTTP_USER_AGENT"], $match) != 0) {
echo '<link href="css/evaStyles_ie.css" rel="stylesheet">';
} else {
if(isset($row)){
echo '
<meta name="theme-color" content="'.$row["akzentfarbe"].'"/>
<style>
:root {
--hintergrund: '.$row["hintergrund"].';
--akzentfarbe: '.$row["akzentfarbe"].';
--schrift: '.$row["schrift"].';
--link: '.$row["link"].';
}
html {
--hintergrund: '.$row["hintergrund"].';
--akzentfarbe: '.$row["akzentfarbe"].';
--schrift: '.$row["schrift"].';
--link: '.$row["link"].';
}
</style>
<link href="css/evaStyles.css" rel="stylesheet">
';
} else {
echo '
<meta name="theme-color" content="'.$appinfo["akzentfarbe"].'"/>
<style>
:root {
--hintergrund: '.$appinfo["hintergrund"].';
--akzentfarbe: '.$appinfo["akzentfarbe"].';
--schrift: '.$appinfo["schrift"].';
--link: '.$appinfo["link"].';
}
html {
--hintergrund: '.$appinfo["hintergrund"].';
--akzentfarbe: '.$appinfo["akzentfarbe"].';
--schrift: '.$appinfo["schrift"].';
--link: '.$appinfo["link"].';
}
</style>
<link href="css/evaStyles.css" rel="stylesheet">
';
}
}
?>
</head>
<body>
<div class="loadScreen">
<span class="helper"></span><img class="img-responsive" id="loadingImg" src="img/loading.svg"/>
</div>
<div id="pageContents" style="opacity: 0;">
<!-- Navigation -->
<div id="naviLink">
<nav class="navbar navbar-expand-lg navbar-inverse bg-color fixed-top" id="slideMe" style="display: none;">
<div class="container">
<a class="navbar-brand" href="modul/dashboard/dashboard.php">
<img src="<?php echo $appinfo["logo_path"];?>" width="<?php echo $appinfo["logo_width"];?>" alt="Logo">
<span style="margin-left:20px;"><?php echo $appinfo["title"];?></span>
</a>
<button class="navbar-toggler custom-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<?php
$userID = ($mysqli->query("SELECT ID FROM tb_user WHERE bKey = '$session_username'")->fetch_assoc());
$sql1 = "SELECT mg.ID, mm.file_path, mm.title FROM tb_ind_nav AS mg INNER JOIN tb_modul AS mm ON mm.ID = mg.tb_modul_ID WHERE mg.tb_user_ID = " . $userID['ID'] . " ORDER BY mg.position";
$result = $mysqli->query($sql1);
if (isset($result) && $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$link = '
<li class="nav-item">
<a class="nav-link" navLinkId="'. $row["ID"].'" href="'. $row["file_path"].'">'. $translate[$row["title"]].'</a>
</li>
';
echo $link;
}
} else {
$link = '
<li class="nav-item" id="editNavLink">
<a class="nav-link" href="modul/settings/settings.php">'. $translate[15].'</a>
</li>
';
echo $link;
}
?>
</ul>
</div>
</div>
</nav>
</div>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-10 offset-md-1">
<div page="<?php if(isset($_SESSION["user"]["currentPath"])){ echo $_SESSION["user"]["currentPath"]; } else { echo "modul/dashboard/dashboard.php";} ?>" id="pageContent">
</div>
</div>
</div>
</div>
<!-- /.container -->
<footer class="footer" id="slideMeFoot" style="display: none;">
<div class="container">
<a class="foot-link" href="modul/settings/settings.php"><?php echo $translate[16] ?></a><i class="text-muted"> | <?php echo $_SESSION["user"]['username']; ?></i><span class="text-muted">© HTML Link | 2018 | <?php echo $appinfo["title"];?> v.1.0</span>
</div>
</footer>
</div>
<!-- Bootstrap core JavaScript -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<!-- Own JS -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<script type="text/javascript">
var translate = {};
<?php
foreach ($translate as $key => $value) {
echo ("translate['".$key."'] = '".$value."';");
};
?>;
</script>
<script src="js/index.js"></script>
</body>
</html>
If you are using arrow syntax like value.foreach(param => {}); It can also cause this error in IE 11 since it does not understand shorthand functions. Need to change the function to be: value.foreach(function(param){});
The problem probably resides in your dashboard.js file. On line 4 you have a setInterval():
var id = setInterval(frame, speed, );
There is either a parameter missing or you accidentally added an extra comma.
To reproduce this you can include the dashboard.js file on any page and the syntax error will be displayed.

How to show message that user is already registered in html through php?

I have an HTML form in which a user enter his/her email id to register everything is working great it checks the valid email id and also registered the email id ! But when I applied new code to check that the user is already registered or not it didn't work !!
Below is my Html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign Up - MOBTRICKS</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Lato:400,700'>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="assets/ico/fa.png">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<!-- <script type="text/javascript">
function greeting(){
alert("Welcome ! Your Email : " + document.forms["form"]["email"].value + " has been registered under our records successfully !")
}
</script> -->
</head>
<body>
<!-- Header -->
<div class="container">
<div class="row header">
<div class="col-sm-4 logo">
<h1><a href=#>PQR</a> <span>.</span></h1>
</div>
<div class="col-sm-8 call-us">
<p>Mob: <span>+91-9530803237</span> | email: <span>ab.creations27#gmail.com</span>
</p>
</div>
</div>
</div>
<!-- Coming Soon -->
<div class="coming-soon">
<div class="inner-bg">
<div class="container">
<div class="row">
<div class="col-sm-12">
<center>
<i class="fa fa-cog fa-spin fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
<h2>We're Coming Soon</h2>
<p>We are working very hard on the new version of our site. It will bring a lot of new features. Stay tuned!</p>
<div class="timer">
<div class="days-wrapper">
<span class="days"></span>
<br>days
</div>
<div class="hours-wrapper">
<span class="hours"></span>
<br>hours
</div>
<div class="minutes-wrapper">
<span class="minutes"></span>
<br>minutes
</div>
<div class="seconds-wrapper">
<span class="seconds"></span>
<br>seconds
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Content -->
<div class="container">
<div class="row">
<div class="col-sm-12 subscribe">
<h3>Subscribe to our newsletter !!</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" role="form" action="assets/subscribe.php" method="post">
<div class="form-group">
<label class="sr-only" for="subscribe-email">Email address</label>
<input type="text" name="email" placeholder="Enter your email..." class="subscribe-email form-control" id="subscribe-email">
</div>
<button type="submit" class="btn">Subscribe</button>
</form>
***
<div class="success-message"></div>
<div class="error-message"></div>***
</div>
</div>
<div class="row">
<div class="col-sm-12 social">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<a href="https://github.com/ashu271994" data-toggle="tooltip" data-placement="top" title="GitHub">
<i class="fa fa-github"></i>
</a>
<i class="fa fa-google-plus"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-envelope-o"></i>
</div>
</div>
</div>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ASHISH BHARWAL
</li>
<li>Credits: AB-Creations
</li>
</ul>
</footer>
<!-- Javascript -->
<script src="assets/js/jquery-1.11.1.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
ipt src="assets/js/jquery.backstretch.min.js"></script>
<script src="assets/js/jquery.countdown.min.js"></script>
<script src="assets/js/scripts.js"></script>
<!--[if lt IE 10]>
<script src="assets/js/placeholder.js"></script>
<![endif]-->
</body>
</html>
Below is my Subscriber.php page
<?php
// Email address verification
function isEmail($email)
{
return (preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]| [[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if ($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'ab.creations27#gmail.com';
$subscriber_email = addslashes(trim($_POST['email']));
if (!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
// $msg="wrong answer";
// echo "<script type='text/javascript'>alert('$msg');</script>";
} else {
$host = "somehostname";
$user = "username";
$pwd = "password";
$db = "demo1";
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
$stmt1 = $conn->prepare($sql_insert);
$stmt1->execute();
$result = $stmt1->fetchColumn();
if ($result == 0) {
$sql_insert = "INSERT INTO demotable (subs)
VALUES ('$subscriber_email')";
$stmt = $conn->prepare($sql_insert);
$stmt->execute();
$array = array();
$array['valid'] = 1;
$array['message'] = "Your Email : $subscriber_email has been registered with us ! Thanks for your subscription!";
echo json_encode($array);
} else {
$array = array();
$array['valid'] = 2;
$array['message'] = "You are already registered !!";
echo json_encode($array);
}
}
catch (Exception $e) {
die(var_dump($e));
}
}
}
?>
Now what is happening when I tried to add an invalid email id then it shows Invalid Email id in marked in HTML page but when I added a new user then add the data in my table and show message but in case of the user who is already registered it didn't show any message !! I also tried to make new functions having "echo json_encode($array)"; But this also won't work !! Tell me what am I missing or what's my mistake !! I am trying to sort it from the last 3 days !!
my scripts.js code below
$('.subscribe form').submit(function(e) {
e.preventDefault();
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'assets/subscribe.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else if (json.valid == 1){
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
else {
$('.error-message').hide().empty();
$('.success-message').hide().empty();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});
Try changing
$result = $stmt1->fetchColumn();
to
$result = $stmt1->num_rows;
see if that works.
Finally got it working. The error was simple but yet difficult to find. lolz
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
should be like
** $sql_insert = "SELECT COUNT(*) FROM demotable WHERE subs='$subscriber_email'";**
Thank you all for your views. :)

Results change without page load

I am working on a site. If you select city "Karachi" it would show you results. I want to filter the results. I have added the filter options. I am looking for ways to interact with the database so the results change as I select a filter. Please guide.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Tuition Teacher</title>
<!-- Custom styles for this template -->
<link href="sticky-footer-navbar.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
.navbar-nav{
float:right;
}
#slider-range, #slider-range2 {
width:300px;
margin-top:10px;
}
#slider-range2.ui-slider-horizontal {
border: 0 none;
}
#slider-range2.ui-slider-horizontal .ui-slider-range, #slider-range2.ui-slider-horizontal .ui-slider-handle {
background: url("http://unbug.ru/examples/jquery/slider/slide.png") repeat scroll 0 0 transparent;
}
#slider-range2.ui-slider-horizontal .ui-slider-range {
background-position: 0 -42px;
background-repeat: repeat-x;
height: 21px;
}
#slider-range2.ui-slider-horizontal .ui-slider-handle {
background-position: 0 0;
background-repeat: no-repeat;
border: 0 none;
height: 21px;
top: 0;
width: 21px;
}
#slider-range2.ui-slider-horizontal .ui-slider-handle:focus {
outline: 0 none;
}
#slider-range2.ui-slider-horizontal .ui-slider-handle + .ui-slider-handle {
background-position: -21px 0;
}
</style>
<script>
$(function() {
var availableTags = [
"Lahore",
"Karachi",
"Islamabad",
"Rawalpindi",
"Faisalabad",
"Multan",
"Gujranwala",
"Quetta",
"Peshawar",
"Hyderabad",
"Sialkot"
];
$( "#city" ).autocomplete({
source: availableTags
});
});
</script>
<script>
$(document).ready(function() {
$(function() {
$( "#slider-range, #slider-range2" ).slider({
range: true,
min: 15,
max: 100,
values: [15, 100 ],
slide: function( event, ui ) {
$( "#amount" ).val(ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
}
});
$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
" -" + $( "#slider-range" ).slider( "values", 1 ) );
});
});
</script>
</head>
<body>
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!--
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>^
</div>
-->
<div id="navbar" class="collapse navbar-collapse text-right">
<ul class="nav navbar-nav ">
<li >Teachers Log In </li>
<li>Teachers Sign Up</li>
<li>Tour</li>
<!--Sign Up
<li class="dropdown">
Dropdown <span class="caret"></span>
<ul class="dropdown-menu">
<li>Action</li>
<li>Another action</li>
<li>Something else here</li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li>Separated link</li>
<li>One more separated link</li>
-->
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<!-- Begin page content -->
<div class="container">
<div class="row">
<div class="col-md-3">
<h2>Filter</h2>
City:<br>
<input id="city" placeholder="<?php echo $_POST['city'] ?>">
<br>
Gender:<br>
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female<br>
<p>
<label for="amount">Age range:</label>
<input type="text" id="amount"/>
</p>
<div id="slider-range"></div>
Education:<br>
<input type="radio" name="education" value="high school">High School<br>
<input type="radio" name="education" value="intermediate">Intermediate<br>
<input type="radio" name="education" value="professional degree">Professional Degree<br>
</div>
<div class="col-md-9">
<h2>Search Results</h2>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$city = $_POST["city"];
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city='$city'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Name:" . $row["full_name"]."<br> Email:". $row["email"]. "<br>City: " . $row["city"]. "<br>Age: " . $row["age"]. "<br>Contact Number:". $row["contact_number"]. "<br> Gender: " . $row["gender"]. "<br>Education:" . $row["education"];
echo "<br><hr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
</div>
</div> <!-- Container ends -->
<footer class="footer">
<div class="container">
<div class="row">
<p class="text-muted text-left col-md-6">Copyright 2015. All Rights Reserved.</p>
<p class="text-muted text-right col-md-6">Facebook - Twitter - LinkedIn.</p>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="dropdown.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="ie10-viewport-bug-workaround.js"></script>
</body>
</html>
Using ajax. It is technology that allow you:
Update a web page without reloading the page.
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded.
Send data to a server - in the background
A simple ajax syntax is:
jQuery.ajax({
type: 'POST',
url: "index.php?task=testfunction",
data: '',
dataType: 'html',
beforeSend: function() {
//do function show when loading
},
success : function(result) {
//do function show when success
jQuery('#result').html(result);
}
});
In php you have to write
<?php
function testfunction(){
echo 'This is result';
die;
}
?>

Fancybox not working on CakePHP

I am trying to make a gallery, which has multiple thumbs that should popup the original image when someone clicks on them, like in the first example in the instructions page on fancybox2 page.
After multiple failed attempts, some of which where even the thumbs were not showing up. I have been suggested to use the CakePHP-Fancybox to fix this, which solved half problem. When someone clicks on the thumbs, that user is being redirected to another page that show the original image, instead of making it float on the gallery itself.
Now I get an Uncaught TypeError: Object [object Object] has no method 'fancybox' in the $(".fancybox3").fancybox({. How can this issue be fixed?
Controller:
public function ShowImages(){
$this->layout = 'default';
$this->loadModel('GalleryImage');
$gallery_images = $this->GalleryImage->find('all');
$this->set('gallery_images', $gallery_images);
//$image_display = $gallery_image['path']
}
View:
<h2>Galeria</h2>
<br>
<table width="100%">
<tr>
<?php
$i=0;
foreach( $gallery_images as $gallery_image ):?>
<td align="center" class="thumbnail" style="display:inline-block;">
<?php
$src3 =$this->webroot. 'img/gallery/' .$gallery_image['GalleryImage']['path'];
//$src3 = 'img/gallery/' .$gallery_image['GalleryImage']['path'];
$this->Fancybox->setProperties( array(
'class' => 'fancybox3',
'className' => 'fancybox.image',
'title'=>'Single Image',
'rel' => 'gallery1'
)
);
$this->Fancybox->setPreviewContent($this->Timthumb->image('/img/gallery/' . $gallery_image['GalleryImage']['path'] , array('width' => 267, 'height' => 189)));
$this->Fancybox->setMainContent($src3);
echo $this->Fancybox->output();
?>
</td>
<?php $i++;
if($i==4){
echo "</tr><tr>";
$i=0;
}
?>
<?php endforeach ?>
</tr>
</table>
Layout (head):
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title><?php echo $title_for_layout;//titulo dinamico da página?></title>
<?php
echo $this->Html->meta('icon');
//echo $this->Html->css('cake.generic');
echo $this->fetch('meta');
//echo $this->fetch('css');
echo $this->Html->script('jquery-1.11.0.min');
echo $this->Html->script('jquery.fancybox.pack.js?v=2.1.5');
echo $this->Html->script('main');
echo $this->Html->css('main');
echo $this->Html->script('modernizr-2.6.2-respond-1.1.0.min');
echo $this->Html->css('bootstrap-theme.min');
echo $this->Html->css('bootstrap.min');
echo $this->Html->css('bootstrap');
echo $this->Html->script('bootstrap.min');
echo $this->Html->script('bootstrap');
echo $this->Html->script('dropdown');
echo $this->Html->script('collapse');
?>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<style>
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<script type="text/javascript">
$(function(){
$(".dropdown-toggle").click(function(){
$(this).dropdown('toggle');
});
});
</script>
<!-- src="/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"-->
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php
$home_link_image= $this->webroot."img/PushUp.png";
if(!$this->Session->check('Admin')){
$home_link = "/html/PushUp_app/";
}
else{
$home_link = "/html/PushUp_app/admins/admin_index";
}
echo "<a class=\"pushup_logo\" href=\"".$home_link."\">";
//echo" <img src=\"".$home_link_image."\" name=\"logo\" id=\"logo\"/>";
?>
</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<?php
//if(!$this->Session->check('User')){
echo $this->Html->link('Home', array('controller'=>'home', 'action'=>'index'));
//}
/*else{
echo $this->Html->link('Administrador', array('controller'=>'admins','action' =>'admin_index'));
}*/
?>
</li>
<li class="dropdown">
Serviços <b class="caret"></b>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link('Música', array('controller'=>'services', 'action'=>'Musica'))?></li>
<li><?php echo $this->Html->link('Animação Temática', array('controller'=>'services', 'action'=>'AnimacaoTematica'))?></li>
<li><?php echo $this->Html->link('Promoção', array('controller'=>'services', 'action'=>'Promocao'))?></li>
<li><?php echo $this->Html->link('Staff', array('controller'=>'services', 'action'=>'Staff'))?></li>
<li><?php echo $this->Html->link('Aluguer', array('controller'=>'services', 'action'=>'Aluguer'))?></li>
</ul>
</li>
<li class="dropdown">
Galeria<b class="caret"></b>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link('Fotografias', array('controller'=>'galleries', 'action'=>'ShowImages'))?></li>
<li><?php echo $this->Html->link('Videos', array('controller'=>'galleries', 'action'=>'ShowVideos'))?></li>
</ul>
</li>
<li><?php echo $this->Html->link('Cartaz', array('controller'=>'showbills', 'action'=>'ShowShowbill'))?></li>
<li><?php echo $this->Html->link('Contactos', array('controller'=>'contacts', 'action'=>'ShowContactUs'))?></li>
<li><?php
/* if(!$this->Session->check('User')){
echo $this->Html->link('Log-in', array('controller'=>'users','action' =>'login'));
}
else{
echo $this->Html->link('Log-out', array('controller'=>'users','action' =>'logout'));
}*/
?>
</li>
</ul>
</li>
</ul>
<!--<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>-->
</div><!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
</div>
</div>
<div class="container">
<?php echo $this->Session->flash();?>
<!-- Example row of columns --><?php echo $this->fetch('content');?><!--carrega o conteudo para a página-->
<div class="row">
<div class="col-lg-4">
</div>
</div>
<hr>
<footer>
<p>© Company 2013</p>
</footer>
</div> <!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.1.min.js"><\/script>')</script>
<!--<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/main.js"></script>-->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src='//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
<script type="text/javascript" >
$(document).ready(function() {
$(".fancybox3").fancybox({
openEffect : 'none',
closeEffect : 'none',
helpers : {
title : {
type : 'image'
}
}
});
});
</script>
<?php echo $this->Js->writeBuffer(); ?>
</body>
</html>
If you follow CakePHP-Convention you will put your Fancybox-Mediacontent into your "App/webroot/img/fancybox-media/" - Directory. If so, you're able to access the Media like:
http://www.my-app.com/img/fancybox-media/
The nice way building casual DOM-Elements in your View is using Cake's Form-Helper:
In your AppController:
class AppController extends Controller {
public $helpers = array('Form', 'Session', 'Html');
// Rest of your Code here
}
After that you'll be possible to replace the following line with the one below in your View:
Replace:
echo "<a href=\"gallery/" . $gallery_image['GalleryImage']['path'] . "\"class=\"fancybox_img\">";
echo $this->Html->image('gallery/' . $gallery_image['GalleryImage']['path'] . '', array('width' => '189px', 'height' => '267px', 'alt' => $gallery_image['GalleryImage']['path'] ));
echo "</a>";
With:
$this->Html->link(
$this->Html->image('gallery/' . $gallery_image['GalleryImage']['path'], array('width' => '189px', 'height' => '267px', 'alt' => $gallery_image['GalleryImage']['path'] )
);
And please be sure that your $gallery_image['GalleryImage']['path'] - Variable stores the name of the Image-File. Also ensure the existance of the Image (Case-Sensitive) in "App/webroot/gallery/myImage.jpeg"
Additionally post eventual thrown JS-Errors in your Browsers Dev-Console if you have one. (Try F12)

Categories

Resources