When i try to send mail with the code the send button stays in "sending" and never changes to "sent". But mail is actuall sent to my mail box...
You can check in site secco.uni.me
Thanks.
The html code of main page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Sun and Moon Calculations</title>
<link rel="shortcut icon" href="site_icon.png">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="robots" content="index,follow">
<meta name="description" content="Calculate local sunrise, sunset, moonrise, moonset and moon illumination with a click on map. Learn your time zone. Great tool for photographers and hunters as well as security forces. ">
<link rel="stylesheet" type="text/css" href="secco.css">
<link href="fancybox/source/jquery.fancybox.css" media="all" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD2rBJhT2rjQwA3jVKYrbbElkkm525UabU&sensor=false"></script>
<script type="text/javascript" src="map.js"></script>
<script type="text/javascript" src="time.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="fancybox/source/jquery.fancybox.js?v=2.0.6"></script>
</head>
<body>
<img alt="Under Construction" src="ribbon.png" width="132" height="100" style="position: absolute; top: 0; right: 0; border: 0;">
<script src="moon.js"></script>
<center>
<h2>Sun and Moon Calculations</h2>
<div id="bd">
<div id="gmap"></div>
<!--Lat: <span id="lat"></span> Lon: <span id="lon"></span><br/>
Zoom Level: <span id="zoom_level"></span> -->
<div id="expl"><h5>*Click <span style="color:red">red</span> marker for exact coordinates.
Center the map, then hit buttons for calculations. Your feedback is valuable...<h5></div>
</div>
<div id="form">
<form name=calc>
<table border="" cellspacing=5 bordercolor=white frame=void rules=rows>
<tr>
<td>Latitude <td><INPUT size=20 maxLength=10 name=lat>
<td>RAW Offset<td><INPUT readOnly size=35 maxLength=35 name=rawoffset>
<td>Moonrise <td><INPUT readOnly size=20 maxLength=20 name=moonrise>
<tr>
<td>Longitude <td><INPUT size=20 maxLength=20 name=lon>
<td>DST Offset<td><INPUT readOnly size=35 maxLength=35 name=dstoffset>
<td>Moonset<td><INPUT readOnly size=20 maxLength=20 name=moonset>
<tr>
<td>Zoom Level<td><INPUT readOnly size=20 maxLength=20 name=zl>
<td>Time Zone ID <td><INPUT readOnly size=35 maxLength=35 name=timezoneid>
<td>Moon Phase<td><INPUT readOnly size=20 maxLength=20 name=moonphase>
<tr>
<td>This Day <td><INPUT readOnly size=20 maxLength=20 name=thisday>
<td>Time Zone <td><INPUT readOnly size=35 maxLength=35 name=timezone>
<tr>
<td>Timestamp <td><INPUT readOnly size=20 maxLength=20 name=timestamp>
</table>
</form>
</div>
<input type="button" onclick="setLocation()" value="Set Location">
<input type="button" onclick="compute()" value="Moon Calculation">
<input type="button" onclick="sun()" value="Sun Calculation"><br>
</center>
<!-- Feedback mail post section-->
<!-- hidden inline form -->
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
<script type="text/javascript" src="mailpost.js"></script>
<!-- BOTTOM STUFF -->
<div id="bottom">
<script language="JavaScript">
initdate();
var count = "secco"; // Change Your Account?
var type = "war2orc"; // Change Your Counter Image?
var digits = "7"; // Change The Amount of Digits on Your Counter?
var prog = "hit"; // Change to Either hit/unique?
var statslink = "no"; // provide statistical link in counter yes/no?
var sitelink = "yes"; // provide link back to our site;~) yes/no?
var cntvisible = "yes"; // do you want counter visible yes/no?
</script>
<!-- START DO NOT TAMPER WITH ANYTHING ELSE BELOW THIS LINE FOR YOUR WEBTV & UNIX VISITORS -->
<img src="jquery-logo.png" width="70" height="15" style="position: relative;width:95% text-align:left;top:3px; left:60px;"/>
<img src="google-maps-api-v3.png" width="70" height="15" style="position: relative;width:95% text-align:left;top:3px; left:-90px;"/>
<a class = "modalbox" href="#inline"><img src="icon_mailto.gif" style="position: relative;width:95% text-align:right;top:3px; left:-8px;"/></a>
<script language="JavaScript" src="http://005.free-counters.co.uk/count-072.js">
</script>
<noscript>
<a href="http://www.free-counters.co.uk" target="_blank">
<img src="http://005.free-counters.co.uk/count-072.pl?count=secco&cntvisible=no&mode=noscript" style="position: absolute;" alt="Free Counters" title="Free Counters" border="0">
</a>The following text will not be seen after you upload your website,
please keep it in order to retain your counter functionality
<br>Trackers<br> Counter Help<br>
</noscript>
<!-- END DO NOT TAMPER WITH ANYTHING ELSE ABOVE THIS LINE FOR YOUR WEBTV & UNIX VISITORS -->
</div>
</CENTER>
</body>
</html>
My mailpost.js file:
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
And sendmessage.php file
<?php
$sendto = "mail#hotmail.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
You set the text to "sending..." with this:
$("#send").replaceWith("<em>sending...</em>");
But you never set it to anything else after that. So, it stays put. If you want to change it, you can add a line to your success function, like this:
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
$("#send").replaceWith("<em>sent!</em>"); // This is the line to add.
}
}
PHP Code
if(#mail($sendto, $subject, $msg, $headers)) {
echo "1";
} else {
echo "0";
}
AJAX code:
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == 1) {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
I changed the true and false echo responses to 0 and 1.
I suppose there is a problem about js code about fetching the return from php code. Anyway the code runs as it is supposed to. Thanks.
Change this line
if(#mail($sendto, $subject, $msg, $headers)) {
to
if(mail($sendto, $subject, $msg, $headers)) {
Additionally, I recommend using die("true"); or removing the closing PHP tag otherwise you risk having a confusing new line at the end of the file that can potentially produce undesired results.
Related
I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>. Image Dump...</p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">😀</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="↑" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.
here I am trying to submit a form.what i want to know is when user enters his firstname if that firstname is already in the database how can i prevent him from from submitting the form and give a error message.It should check first name when he is typing.
Here is my code
if(isset($_POST['btn-signup']))
{
$reqnum = $_POST['reqnum'];
$Mnumber = $_POST['Mnumber'];
$email = $_POST['email'];
$fname = $_POST['fname'];
$address = $_POST['address'];
$sitename = $_POST['sitename'];
$payment = $_POST['payment'];
//if()
//{
$new_fname= $_POST['fname'];
$xxx = mysql_query("SELECT fname FROM gotest WHERE fname = '$new_fname'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0)
{
$query = mysql_query("INSERT INTO gotest(Mnumber,email,fname,address,sitename,reqnum,payment) VALUES('$Mnumber','$email','$fname','$address','$sitename','$reqnum','$payment')");
$r = mysql_insert_id();
header("Location: http://uuuu.yyyyy.net/test/freecreate.php?rid=$r");
}
else
{
echo"error";
}
}
Here is my form
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>gooooooooo </title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<link rel="stylesheet" type="text/css" href="demo/demo.css" >
<link rel="stylesheet" href="demo/codemirror.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/additional-methods.min.js"></script>
<!--<script src="script.js"></script>-->
<script type="text/javascript">
function copyText() {
src = document.getElementById("fname");
dest = document.getElementById("sitename");
dest.value = src.value;
}
</script>
</head>
<body>
<div class="wrapper">
<header>
<img src="images/logo.png" width="200" align="center" id="logo" style="text-align: center" />
</header>
<div id="login-form" style="margin-top: 5px !important;">
<form action="" method="post">
<table align="middle" border="0" style="margin: 0 auto; background: rgba(57, 134, 79, 0.64);" >
<h1 align="middle" style="color: #fff">Create Your Web Site</h1></br></br>
<tr>
<td><input type="text" id="Mnumber" name="Mnumber" value="" placeholder="Your Mobile Number" required /></td>
</tr>
<tr>
<td><input type="email" id="email" name="email" value="" placeholder="Your Email" required /></td>
</tr>
<tr>
<td><input type="text" id="fname" name="fname" value="" placeholder="Your First Name" onkeyup="copyText()" required /></td>
</tr>
<tr>
<td><input type="text" id="address" name="address" value="" placeholder="Your Address" required /></td>
</tr>
<tr>
<td><input type="text" id="sitename" name="sitename" value="" placeholder="Your Site name" readonly/></td>
</tr>
<tr>
<td><button type="submit" id="btn-signup" name="btn-signup" style="background: #39864f; border: 1px solid #fff; cursor: hand">Create website</button></td>
</tr>
</table>
</form>
<script>
</script>
</div>
<footer>
<p style="text-align: center;">Powered By <img src="images/elogo.png" align="center" id="logo" style="text-align: center; height: 40px; width: 153px;padding-bottom: 10px;" /></p>
</footer>
</div>
</body>
</html>
You just need to alter the condition because mysql_num_rows() returns number of rows fetched from database with your query.
Your query is for selecting number of rows which contains new_fname. This will return 1 if record available with that name.
So you need to check mysql_num_rows($xxx)>0, then echo error else do your work.
if(mysql_num_rows($xxx) > 0)
{
echo"error";
}
else
{
$query = mysql_query("INSERT INTO gotest(Mnumber,email,fname,address,sitename,reqnum,payment) VALUES('$Mnumber','$email','$fname','$address','$sitename','$reqnum','$payment')");
$r = mysql_insert_id();
header("Location: http://uuuu.yyyyy.net/test/freecreate.php?rid=$r");
}
Using AJAX - Prevent user to submit form.
You can check by ajax as following
You need to attach jquery library to use jquery functions
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn-signup").attr('disabled', true); // This will disable submit button.
$("#fname").keyup(function(){
var fname = $(this).val();
$.ajax({
url: "check_name.php",
type: "POST",
data: {fname : fname }
success: function(response){
if(response=="ok")
{
$("#btn-signup").attr('disabled', false); // Enable submit button.
}
else
{
alert("Fname is already exist.");
$("#btn-signup").attr('disabled', true);
}
}
});
})
})
</script>
Your php script to check name already exist or not
check_name.php
<?php
$new_fname= $_POST['fname'];
$xxx = mysql_query("SELECT fname FROM gotest WHERE fname = '$new_fname'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0)
{
echo "exist";
}
else
{
echo "ok";
}
?>
I have a site I'm working on Modestewebstudio.com
On the contact section of the site I have a form that I'm trying to submit using jQuery and pHp. For some reason the form does not submit. The validation works fine but whenever I hit submit nothing happens.
$(document).ready(function () {
$(window).load(function() { $("#load").fadeOut("slow"); });
var fadeInElement = function(id) {
$('#' + id).fadeIn();
};
//HOME-------------------------------------------------
$(".home").click(function () {
$('#about, #works, #contact').filter(":visible").fadeOut();
fadeInElement('home');
});
//ABOUT------------------------------------------------
$(".about").click(function () {
$('#home, #works, #contact').filter(":visible").fadeOut();
fadeInElement('about');
});
//WORKS------------------------------------------------
$(".works").click(function () {
$('#home, #about, #contact').filter(":visible").fadeOut();
fadeInElement('works');
});
//CONTACT----------------------------------------------
$(".contact").click(function () {
$('#home, #about, #works').filter(":visible").fadeOut();
fadeInElement('contact');
});
<!--//--><![CDATA[//><!--
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Your '+labelText+' is missing.</span>');
$(this).addClass('inputError');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Your '+labelText+' is invalid.</span>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p>Your email has been delivered!</p>');
});
});
}
return false;
});
//-->!]]>
//-----------------------------------------------------
});
<?php
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = 'Forgot your name!';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = 'Forgot to enter in your e-mail address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = 'You forgot to enter a message!';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
// upon no failure errors let's email now!
if(!isset($hasError)) {
$emailTo = 'zenneson#gmail.com';
$subject = 'Submitted message from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
// set our boolean completion value to TRUE
$emailSent = true;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Denneson Modeste</title>
<!--Fonts-->
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Syncopate' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Special+Elite' rel='stylesheet' type='text/css'>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="load">
<div class="load-logo pulse"></div>
<p>Loading</p>
</div>
<div class="tv"></div>
<div class="home tv-btn">HOME</div>
<div class="about tv-btn">ABOUT</div>
<div class="works tv-btn">WORKS</div>
<div class="blog tv-btn">BLOG</div>
<div class="contact tv-btn">CONTACT</div>
<div id="home" class="channel">
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/JdRO97mFMx8?rel=0&controls=0&autoplay=1&showinfo=0&disablekb=1&disablekb=1&modestbranding=1&start=7&loop=1&playlist=JdRO97mFMx8&wmode=opaque" frameborder="0" allowfullscreen></iframe>
</div><!-- end of home -->
<div id="about" class="channel">
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/JdRO97mFMx8?rel=0&controls=0&autoplay=1&showinfo=0&disablekb=1&disablekb=1&modestbranding=1&start=7&loop=1&playlist=JdRO97mFMx8&wmode=opaque" frameborder="0" allowfullscreen></iframe>
</div><!-- end of about -->
<div id="works" class="channel">
</div><!-- end of works -->
<div id="contact" class="channel">
<div class="contact-border"></div>
<div class="stamp"></div>
<div class="contact-section">
<h3>Have a question or wanna say hello? Leave a message below.</h3>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<p class="info">Your message was sent and will be responded to ASAP.</p>
<?php } else { ?>
<form id="contact-us" action="contact.php" method="post">
<?php if(isset($hasError) || isset($captchaError) ) { ?>
<p class="alert">There was a mistake in the message</p>
<?php } ?>
<label>Name</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="txt requiredField" placeholder="Name:" />
<?php if($nameError != '') { ?>
<br /><span class="error"><?php echo $nameError;?></span>
<?php } ?>
<label>E-mail</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />
<?php if($emailError != '') { ?>
<br /><span class="error"><?php echo $emailError;?></span>
<?php } ?>
<label>Message</label>
<textarea name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<br /><span class="error"><?php echo $commentError;?></span>
<?php } ?>
<button name="submit" type="submit" class="subbutton"> </button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</div><!-- end of contact-section -->
<?php } ?>
</div>
</div>
</div><!-- end of contact -->
<!--Javascript-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/application.js"></script>
</body>
</html>
Submitting the form results in the following error
404 (Not Found) http://modestewebstudio.com/contact.php
Make sure there that the file is in fact named contact.php, and that it's placed in the root directory of your web server.
//index.php
<?php
include("config.inc.php");
if(!empty($_GET['email'])){
$dude = $_GET['email']; // user email address to be gotten by javascript variable
// dude and sent to fetch_pages.php
echo '<input type="text" style="display:none" id="hide" value="'. $dude .'" />';
}
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM user_registration_details");
$get_total_rows = mysqli_fetch_array($results); //total records
$item_per_page = 5;
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i< $pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
<?php
/*
* Ajax form submit
*/
# request sent using HTTP_X_REQUESTED_WITH
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['name']) AND isset($_POST['email']) AND isset($_POST['subject']) AND isset($_POST['message'])) {
$to = 'your#mail.id';
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$sent = email($to, $email, $name, $subject, $message);
if ($sent) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
/**
* email function
*
* #return bool | void
**/
function email($to, $from_mail, $from_name, $subject, $message){
$header = array();
$header[] = "MIME-Version: 1.0";
$header[] = "From: {$from_name}<{$from_mail}>";
/* Set message content type HTML*/
$header[] = "Content-type:text/html; charset=iso-8859-1";
$header[] = "Content-Transfer-Encoding: 7bit";
if( mail($to, $subject, $message, implode("\r\n", $header)) ) return true;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Pagination</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var dude = document.getElementById("hide").value;//variable to be sent to fetch_pages //to present user email
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="profiler.js"></script>
<style type="text/css">
#import url("style2.css");
</style>
<link href="style5.css" rel="stylesheet" type="text/css">
</head>
<body onload="profiler();">
<div id="firstdiv">
<p></p>
<img id="image1" src="2347033609685.jpg" alt="Profile Pic" height="170" width="180" />
<table id="pname"><tr height="49"><td id="name">Richard Berry</td></tr>
<tr id="num"><td>08023818955</td><td width="400">Agent with homes and good event centres</td></tr>
<tr height="20"><td width="200">Specialties: Event Centres / Venue</td>
</tr></table>
<table id="like"><tr><td width="6"></td><td width="31"><img src="2347033609685.jpg" height="27" width="27" /></td>
<td width="71"><img src="yahoo2.PNG" height="27" width="27" /></td></tr>
</table>
<table id="pdetails"><tr><td width="200"><p id="over" onclick="profilerr('pover');" ><button id="o">Overview</button></p></td>
<td width="220"><p id="list" onclick="profile('plist');"><button id="l">Listings()</button></p></td>
<td width="221"><p id="about" onclick="profiles('pabout');"><button id="a">About</button></p></td>
</tr></table>
<div id="pabout" style="display:none">
<table>
<tr><td id="name">About Richard Berry</td></tr>
<tr><td>Firstly, there are two sets of people who come to this hall. The first set are those who just come to watch and/or charge gadgets and the second set are those who come to train.
To the first set of people, we plead that you kindly stay in the waiting area when you visit the hall and far from tables especially when people are playing because most times it serves as a means of distraction and also playing on table is prohibited.
Secondly, to the second set of people who are registered members of the team we are pleading that you should always be in complete sport outfit whenever you come for training and should avoid littering of the hall with nylons, papers, bottles e.t.c
Most especially the new training timetable for the semester is below:</td></tr>
</table></div>
<div id="pover" style="display:none">
<table>
<tr><td id="name">About Richard Berry</td></tr>
<tr><td>Firstly, there are two sets of people who come to this hall. The first set are those who just come to watch and/or charge gadgets and the second set are those who come to train.
To the first set of people, we plead that you kindly stay in the waiting area when you visit the hall and far from tables especially when people are playing because most times it serves as a means of distraction and also playing on table is prohibited.
Secondly, to the second set of people who are registered members of the team we are pleading that you should always be in complete sport outfit whenever you come for training and should avoid littering of the hall with nylons, papers, bottles e.t.c
Most especially the new training timetable for the semester is below:</td></tr>
<tr><td id="listl">Listings (2401) by Richard Berry</td></tr>
</table></div>
<div id="plist" style="display:none">
<table>
<tr><td id="listl">Listings(2401) by Richard Berry</td></tr>
<tr></tr></table>
<div id="results"></div>
<?php echo $pagination; ?>
</div>
</div>
<div id="wrap">
<p id="compdiv">Contact Supplier</p>
<div class="alert">Hello</div>
<form id="form" action="" method="post">
<div>
<label>
<span id="spandisp">Name: * </span>
<input placeholder="Name" type="text" id="input" name="name" required>
</label>
</div>
<div>
<label>
<span id="spandisp">Email: * </span>
<input placeholder="Email address" id="input" type="email" name="email" required>
</label>
</div>
<div>
<label>
<span id="spandisp">Subject: * </span>
<input placeholder="Subject" id="input" type="text" name="subject" required>
</label>
</div>
<div>
<label>
<span id="spandisp">Message: *</span>
<textarea id="input2" placeholder="Type your message here...." name="message" required></textarea>
</label>
</div>
<div>
<button name="submit" type="submit" id="submit">Send Message</button>
</div>
</form>
<p>Note: * Fields are required</p>
</div>
</div>
</body>
</html>
//config.inc.php
<?php
$db_username = 'root';
$db_password = '****';
$db_name = '****';
$db_host = 'localhost';
$item_per_page = 5;
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name) or
die('could not connect to database');
?>
//fetch_pages
<?php
include("config.inc.php"); //include config file
$item_per_page = 5;
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!empty($_POST['email'])){
$email = $_POST['email'];
echo "gotcha";
}
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB,"SELECT * FROM user_registration_details WHERE email = '$email' ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'">'.$row["id"].'. <span class="page_name">'.$row["contact_name"].'</span><span class="page_message">'.$row["email"].'</span><span class="view"> View Details</span></li>';
}
echo '</ul>';
?>
Please the code above is getting the user email from the URL and also successfully inputting it into the JavaScript variable dude. Also all the AJAX pagination script is working perfectly as I want it just that I can't send the user email to fetch_pages.php to be able to restrict the search based a particular user email. please how can I send the user email details to fetch_pages without refreshing the page and not still disturbing the pagination script. please all help will be needed as I need the script for a major project.
i came to understand that the only problem was to add dude to the javascript code as below.
the same webpage cannot send two ajax request to the same php at the same time.
$("#results").load("fetch_pages.php", {'page':0, 'email':(dude)}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1),'email':(dude)}, function(){
});
The program below contains various error messages to be displayed under certain conditions. These conditions are found through PHP code, after which the necessary JQuery script is echoed in PHP to make the messages appear.
At first, all messages in the .warning class are hidden. Then, if a certain condition is met, particular ids of this class are shown. Below is the relevant code.
<?php require_once 'connection.php'; ?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create Account</title>
<link rel="stylesheet" type="text/css" href="Styles2.css">
<script src="JQuery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('.warning').hide();
});
</script>
<div class="unloggedheadingbar">
</div>
<br>
<div class="createaccount">
<center><h1>Create Account</h1></center>
<center><table>
<form action="create_account.php" method="post">
<tr><td><font class="createaccountfont">Email</font></td><td><input type="text" name="Email" placeholder="someone#somewhere.com" value="<?php if(isset($_POST['Create'])){ echo $_POST['Email']; } ?>" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Password</font></td><td><input type="password" name="Password" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Confirm Password </font></td><td><input type="password" name="ConfirmPassword" class="createaccounttext"></td></tr>
</table></center>
<br>
<center><input type="submit" name="Create" value="Create Account" class="createButton" id="Create"></center>
</form>
<br>
<div class="warning" id="passwordMatchError">
<center><font class="warningText">Your password confirmation must match with your original password!</font></center>
</div>
<div class="warning" id="emailFormatError">
<center><font class="warningText">Your email must match the someone#something.com format.</font></center>
</div>
<div class="warning" id="emailDuplicateError">
<center><font class="warningText">An account under this email already exists.</font></center>
</div>
</div>
<?php
if(isset($_POST['Create'])){
$email = $_POST['Email'];
$password = md5($_POST['Password']);
if(strpos($email, '#') !== TRUE){
echo '<script>
$(".warning").hide();
$("#emailFormatError").show();
</script>';
}elseif($_POST['Password'] != $_POST['ConfirmPassword']){
echo '<script>
$(".warning").hide();
$("#passwordMatchError").show();
</script>';
}else{
$query = "SELECT * FROM user_table WHERE Email = '" . $email . "';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0){
$query = "INSERT INTO user_table VALUES ('" . $email . "', '" . $password . "');";
mysqli_query($con, $query);
}else{
echo '<script>
$(".warning").hide();
$("#emailDuplicateError").show();
</script>';
}
}
}
?>
</body>
However, the objects with particular IDs are not actually shown. Does anyone know why this may be? Thank you.
jQuery actions should be placed in $( document ).ready( function () {} );, i.e.:
echo '<script>$( document ).ready( function () {
$(".warning").hide();
$("#emailFormatError").show();
} );</script>';