get selected value from select and post to MySQL Table - javascript

I am fairly new at PHP HTML and found some help on this site but cannot get the code to work as part of my script
On clicking the SUBMIT button a record is posted to the database table (Transactions) but the FIELD (Code) is empty, it should contain a 3 letter uppercase string e.g. ABC
The ALERT shows that the value is stored in the variable $code but an empty string is posted to the table
Your help is greatly appreciated by this novice
<?php
// Include config file
require_once 'config.php';
// Define variables and initialize with empty values
$code = "";
$code_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Validate Code
$code = strtoupper($code);
// Check input errors before inserting in database
if(empty($code_err)){
// Prepare an insert statement
$sql = "INSERT INTO Transactions (Code)
VALUES (?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_code);
// Set parameters
$param_code = $code;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
$url = 'http://localhost:8888/portfolio/index.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<link href="style1.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
.wrapper{
width: 450px;
margin: 0 auto;
}
</style>
<script>
function getValue(obj){
alert(obj.value);
$code=(obj.value);
**alert($code);**
}
</script>
<!--Display heading at top center of screen-->
<div>
<center><h3>Peter's Portfolio - Shares</h3></center>
</div> <!-- end of Div -->
</head>
<body style="background-color:#fcf8d9">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="page-header">
<h2>Create Transaction Record</h2>
</div>
<form class="form-horizontal" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<!-- ASX CODE -->
<div class="form-group">
<label for="name" class="control-label col-xs-6">ASX Code:</label>
<div class="col-xs-6">
<?php
$conn = new mysqli('localhost', 'root', 'root', 'Portfolio') or die ('Cannot connect to db');
$result = $conn->query("SELECT Code, Coy_Nm from Companies ORDER BY Code");
echo "<html>";
echo "<body>";
echo "<select Name='Code' ID='Code'onchange='getValue(this)'>";
while ($row = $result->fetch_assoc()) {
unset($Code, $Coy_Nm);
$Code = $row['Code'];
$Coy_Nm = $row['Coy_Nm'];
echo '<option value="'.$Code.'">'.$Coy_Nm.'</option>';
}
echo "</select>";
echo "<input type='hidden' value='submit'>";
//$code=$_POST['Code'];
//echo $code;
?>
</div>
</div>
<!--Submit and Cancel Buttons-->
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Javascript and PHP cannot simply communicate to each other live.
try this
function getValue(obj){
alert(obj);// check if obj has something in it before proceeding to "value"
alert(obj.value);
}

After require_once 'config.php',
Focus on the following line :
$code = "";
When you submit form and form action is self, this means that your post data will be sent to the same file and when the code is read from your file it makes $code empty every time. of course, an empty value will be sent to DB. move this line inside if condition or change this logic.

Related

Syntax Highlighting PHP SQL

I have a page that searches a database. I am looking to get the data that the user enters in the search box to be highlighted in the search results.
The data from the user is stored in the variable '$criteria', and all contents of that variable I am aiming to highlight.
My PHP looks as follows:
<?php
session_start();
if ($_SESSION['loggedin'] != 1) {
header("Location: ../");
}
include("../php_includes/connection.php");
$queryErrorMessage = "";
?>
<html>
<head>
<title>Search Tasks</title>
<link rel="stylesheet" href="../css/bootstrap.min.css">
<script src="../js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<?php include("header.php"); ?>
<?php include("sidebar.php"); ?>
<div class="row">
<div class="col-md-9">
<div class="well well-lg">
<h3>Search Tasks</h3>
<hr>
<form method="post" action="">
<div class="input-group">
<input name="criteria" type="text" class="form-control" placeholder="What would you like to search for?...">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
Submit
</button>
</div>
</div>
</form>
<?php
//Run section of code if the POST criteria is provided for "criteria"
if(isset($_POST['criteria'])){
$criteria = mysqli_real_escape_string($db,$_POST['criteria']);
//If the user does not provide criteria to search, an error will be displayed.
if($criteria == ""){
$queryErrorMessage = "You did not provide any criteria";
GoTO errorMsg;
}
//Prepare sql statement checking each column with the criteria that is provided.
$sql = "SELECT * FROM taskinfo WHERE clientCompany LIKE '%".$criteria."%' OR clientName LIKE '%".$criteria."%' OR email LIKE '%".$criteria."%' OR contactNo LIKE '%".$criteria."%' OR details LIKE '%".$criteria."%'";
//Run sql query storing the records in $result
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result)>0){
//Get each row and put it into the array $row
echo '<h4>Displaying results for search criteria: <b>'.$criteria.'</b></h4>';
while($row = mysqli_fetch_array($result)){
$queryErrorMessage = "";
//Display the query results
?>
<div class="panel panel-default">
<div class="panel-body">
<h6><b>Task Details:</b></h6>
<?php echo $row['details'];?>
<h6><b>Task Information</b></h6>
<ul>
<li>Client Name: <?php echo $row['clientName'];?></li>
<li>Email: <?php echo $row['email'];?></li>
<li>Phone: <?php echo $row['contactNo'];?></li>
<li>Posted by <b><?php echo $row['postedBy'];?></b></li>
<li>Posted On: <b><?php echo $row['timeAdded']; ?></b></li>
</ul>
</div>
</div>
<?php
}
} else {
$queryErrorMessage = "No records found with your criteria.";
}
} else {
$queryErrorMessage = "Failed to perform query.";
}
}
//Check if there is an error message
//If true, echo the error to the user.
//
//Section of code is called errorMsg to
//Allow it to be called in the code above.
errorMsg:
if($queryErrorMessage != ""){
echo 'An Error Occurred: ';
echo $queryErrorMessage;
}
?>
</div>
</div>
</div>
</body>
</html>
If anyone can help, it'd be much appreciated.
this might help
<?php echo preg_replace_callback('/'.$criteria.'/i', function($matches){
return '<strong>' . $matches[0] . '</strong>';
}, $row['clientName']); ?>
it would make the search keyword in the content bold

How to pass Variable One page to another in php

I have created dynamic button and i need to pass the button ID to another page when my button is clicked. I have pass it but it didn't work
Please give any solution
Here is my code for dash.php:
<?php
session_start();
function dash () {
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if ($result = mysqli_query($db, $sql)) {
$str = '';
while ($row = mysqli_fetch_array($result)) {
// generate array from comma delimited list.
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value.
foreach ($rooms as $v) {
$str .= "<a href = 'booking.php'?btn='btn'><input type='button' name='b1' id='btn' value='" . $v . "' /></a>";
}
}
return $str;
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
Here is my booking.php page:
<?php
if (isset($_POST['btn'])) {
$btn = $_POST['btn'];
echo $btn;
}
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " . $_GET['btn'] . " '";
if ($result = mysqli_query($db, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$RoomNumber = $row['RoomNumber'];
// $RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
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 -->
<title>Customer book Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</style>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title"> Customer booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="RoomNumber" value="<?=$_GET['btn'];?>"required>
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="RoomType" required >
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="Location" required>
</div>
<div class="form-group col-md-12">
<label for="charges">Facilities*</label>
<input type="text" class="form-control input-sm" name="Facilities" required>
</div>
<div class="form-group col-md-12">
<label for="charges">ChargesPerDay*</label>
<input type="text" class="form-control input-sm" name="ChargesPerDay" required>
</div>
<div class="form-group col-md-4">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="FirstName" required>
</div>
</div>
</form>
</div>
</body>
</html>
Try to use $_GET instead of $_POST
if (isset($_GET['btn'])) {
$btn = $_GET['btn'];
echo $btn;
}
Try linking using a form. BUTTONID should be the value to pass. $str should be:
<form action='booking.php' method='POST'>
<input type='hidden' value='BUTTONID' name='bttn'>
<input type='submit' value='".$v."'>
</form>
And then get the value of the hidden field as you already did...
$if (isset($_POST['bttn'])) {
$btn = $_POST['bttn'];
echo $btn;
}
i have modified script of dash.php and booking.php files. Please copy and paste this script.
dash.php file
<?php
session_start();
function dash(){
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value
foreach ( $rooms as $v )
{
$str .= "<input type='button' name='b1' id='btn' value='".$v."' />";
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " .mysqli_error($db);
}
mysqli_close($db);
booking.php file
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " .$_GET['btn']." '";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$RoomNumber=$row['RoomNumber'];
//$RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
To pass little data from one page to another page use parameters in the URL as below is parameter with the value you want to pass to next page as:
Click Button
Then on the anotherpage.php use $_GET to get the value passed by the URL as:
$val = isset($_GET['parameter']) ? $_GET['parameter'] : NULL;
Then use the $val for other processing. I think this may can help you to understand how to pass data from one page to another page simply.
Try to use $_REQUEST by that you can get both GET and POST values.In booking.php print the array like below:
print_r($_REQUEST);
if (isset($_REQUEST['btn'])) {
$btn = $_REQUEST['btn'];
echo $btn;
}

Need an Ajax call to destroy session

I have a script where when a user get verified he/she is brought to Home.php. At the moment Home.php doesn't do much. But in the bottom left hand corner I have a log out button. And as you know when the user clicks on this button he expects his session to be destroyed and for him to be redirected to a log in page. Unfortunately you can't make a click listener in php. I have browsed for an hour looking for a solution but I have not been able to find the right key word or something.
This is my code
EDIT: You only really have to read some code from Home.php the est is only if someoe wants to run the code if they are not sure of their answer
Index.php(Login Page)
<?php
session_start();
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset ($_POST["Username"])&& isset($_POST["Password"]))
{
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$_SESSION["username"] = $Username;
$DB_Check = " SELECT * from users Where username = '".$Username."' and password = '".$Password."' " ;
$result = mysql_query($DB_Check);
if(mysql_fetch_assoc($result) === false){
$error = "invalid username or password";
}else{
header( 'Location: Home.php' ) ;
}
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Index.css"/>
<title>Login</title>
</head>
<body>
<div id="main">
<div class="messages">
<?php
if(isset($error))
echo $error; ?>
</div>
<form action="Index.php" method="post">
<h5>Diary Name:</h5>
<input name="Username" type="text"/>
<h5>Password:</h5>
<input name="Password" type="password"/>
</br>
</br>
</br>
<input name="login" type="submit"/>
</form>
<p>Click HERE to register.</p>
</div>
</body>
</html>
Home.php
<?php
session_start();
echo "Username = " . $_SESSION["username"] . " !";
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$submission = "INSERT INTO `virtualdiary`.`entries` (`entry`) VALUES ('". $entry . "')";
mysql_query($submission);
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Home.css"/>
<title>Home</title>
</head>
<body>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="87">
<?php
if (isset($_POST["entry"])){
echo $entry;
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="LogOut">Log Out</button>
</body>
</html>
From what I have found from searching around I will need a Home.js file with an ajax call. I don't know the first thing about Ajax so I will probably need code to paste or a very blunt tutorial.
Thanks
You could change the logout href to /Logout.php, and in Logout.php have
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
That will simply destroy the users current session, then redirect the user back to the Index.php page.
The AJAX way would be (using jQuery, I can't remember the vanilla JS syntax for ajax calls)
$.ajax({
type: 'GET',
url: '/Logout.php',
success: function(msg) {
if (msg == 'loggedOut') {
window.location.href = 'Index.php';
}
}
});
And then you'd need to change Logout.php, instead of the header line, make it echo/die/print loggedOut (or a json string which would probably be better, but this is just an example).

can I get text from html and put it into variable in php without submitting a form?

I have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps

Get form popup upon successful submission

How do I go about getting this form to display "Submitted" using basic javascript popup window upon successful submission?
<!DOCTYPE html>
<html>
<head>
<title>Site :: </title>
<link rel="stylesheet" media="screen" href="css/wicahost.css" />
<link rel="stylesheet" media="screen" href="css/global.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<?php require_once('inc/php/clearfieldJs.php'); ?>
<script type="text/javascript">
$(document).ready(function() {
$("#splashtease").RSV({
rules: [
"required,emAdd,Please enter your email address.",
"valid_email,emAdd,Please enter a valid email address.",
]
});
});
</script>
</head>
<body>
<script src="http://www.benjaminkeen.com/software/rsv/jquery/jquery.rsv.js"></script>
<div id="splashTeaserBox">
<h1 class="wicasplashcenter">Signup!</h1>
<div class="wicasplashcenter">Captivating interests and inspiring collaboration.</div>
<form id="splashtease" action="inc/subscribe.php" method="post">
<?php $usrBrowser = $_SERVER['HTTP_USER_AGENT']; $todayDt = date('Y-m-d'); ?>
<input type="text" name="emAdd" class="splashtease" value="Your Email Address ..." onFocus="clearText(this)" />
<input type="hidden" name="brwsr" value="<?php echo $usrBrowser; ?>" style="margin:0; padding:0;" />
<input type="hidden" name="dt" value="<?php echo $todayDt; ?>" style="margin:0; padding:0;" />
<input type="submit" name="submit" value="" class="splashteasesub" />
</form>
</div><!--splashTeaserBox--></body>
</html>
PHP
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="dnbame"; // Database name
$tbl_name="subscriber"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
/* Obliterate bad input */
$goodEmail = mysql_real_escape_string($_POST['emAdd']);
$goodBrowser = mysql_real_escape_string($_POST['brwsr']);
$goodDate = mysql_real_escape_string($_POST['dt']);
$sql= "INSERT INTO subscriber (Email, Browser, DateSubscribed) VALUES('$goodEmail','$goodBrowser','$goodDate')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid Email, please retry.');
}
else{
echo var success;
}
?>
A basic example:
In subscribe.php, change:
else{
echo var success;
}
to:
else {
echo "<html><body onload=\"alert('Submitted');\"><p>Submission successful.</p></body></html>";
}
#user886187's solution will reload the page upon submission and then display a JavaScript pop-up when the page has reloaded.
You might want to submit the form and then display the pop-up without reloading the page. In that case you need to submit the form via Ajax, and then alert "submitted" in the callback function:
function callback() {
alert('submitted');
}
Here's a tutorial on how to submit a form via Ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
put this code in your subcribe.php
else {
header ('Location: formPage.php?message=Success');
}
and this code inside head of formPage.php
<head>
<?php if ($_GET['message']) {echo '<script type="text/javascript">alert("Form Submited Successfully");</script>';} ?>
</head>

Categories

Resources