Registration form email verification [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have a script which I have been following a tutorial - I wish to remove the email activation and ensure the users are activated once they hit sign up instead of the activation email being sent and verified?
Here is the script.
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("includes/db_connex.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("includes/db_connex.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$p_hash = md5 ($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir('user/'.$u, 0755, True);
}
// Email the user their activation link
$to = "$e";
$from = "hello#iamdanbarrett.com";
$subject = 'yoursitename Account Activation';
$message = 'message here!'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[" "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, " ") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("includes/template_country_list.php"); ?>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>

To be honest, you should really learn what is going on in the code instead of simply copying it out from a tutorial
The email activation occurs here
// Email the user their activation link
$to = "$e";
$from = "hello#iamdanbarrett.com";
$subject = 'yoursitename Account Activation';
$message = 'message here!'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
so you can simply remove this, and instead of emailing them a verification, just change their status in the database to registered or however you distinguish between someone who hasn't activated their account and someone who has activated their account.

In order to achieve that you'll need to :
1 - learn PHP
2 - There's no 2, you'll just figure it out once you can read the code.

Related

Getting Undefined index when making a session

Hi I'm trying to make a session in my main page but its just giving me an error of undefined index in uniqueID line 5.
The connection between my webqr.js and server.php have no errors but when I tried to connect it to my wow.php it gives me an error of undefined index.
webqr.js Code
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID; }
server.php Code
session_start();
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
wow.php Code
<?php include('server.php');?>
<?php if (isset($_SESSION['unique_id'])) : ?>
Welcome User:
<input type="text" value="<?php echo $_SESSION['unique_id']; ?>" disabled>
<?php endif ?>
Now I'm receiving this error.
okay so this solve my own question.
session_start();
if(isset($_GET['uniqueID'])){
$uniqueID = " ";
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
}
I put my code in another if statement.

Javascript/ajax not sending empty fields to php

I am a beginner in programming and i have a java script function that sends the variables of a form to a php script.
In the form i have two tables that hold two dropdowns each.
I can click the plus button to clone the first table row and i can click delete to remove the clones.
The max amount that can be generated is limited to 3 for nativelang and to 6 for practlang.
I have set all the variables that can be generated in the php and the javascript already and if i generate the max amount then it all works fine.
But if i don't generate any or just a few then the ajax.send is not doing anything, actually the form button stops working.
I suspect it is because of the expected data from the already declared variables that are empty because i didn't generate the drop downs.
This is the code that might cause the problem:
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
and this error is returned:
Uncaught TypeError: Cannot read property 'value' of nullsignup.php:954 signupsignup.php:893 onclick
How can i make it send the field even if its empty? or is it the php code?
I assumed the php would just save the fields that hold data and if a variable has no data then it is just saved as empty into the database right?
So thats why i thought it must be the javascript.
Would be super great if someone could help me to make this work :)
Sign up script:
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var ct = _("city").value;
var nl = _("nativelang").value;
var nll = _("nlanglevel").value;
var nl0 = _("nativelang0").value;
var nll0 = _("nlanglevel0").value;
var nl1 = _("nativelang1").value;
var nll1 = _("nlanglevel1").value;
var nl2 = _("nativelang2").value;
var nll2 = _("nlanglevel2").value;
var pl = _("practlang").value;
var pll = _("planglevel").value;
var pl0 = _("practlang0").value;
var pll0 = _("planglevel0").value;
var pl1 = _("practlang1").value;
var pll1 = _("planglevel1").value;
var pl2 = _("practlang2").value;
var pll2 = _("planglevel2").value;
var pl3 = _("practlang3").value;
var pll3 = _("planglevel3").value;
var pl4 = _("practlang4").value;
var pll4 = _("planglevel4").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || ct == "" || nl == "" || pl == ""){
status.innerHTML = "Fill out all of the form fields marked with a star";
} else if(p1 != p2){
status.innerHTML = "Your passwords do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'Email has been sent!';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.trim()!= "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "<div id=\"status\">OK "+u+", <h2>check your email</h2> inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully <h2>activate your account!</h2></div>";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
}
}
Script for the buttons that add or delete rows in the table(table holds dropdowns):
var ncount = -1;
$(document).ready(function(){
$('#addBtnNative').on('click', function(e){
if($('.nativelangdrop').length < 4) {
ncount++;
var initialn_row = $('tr.initialn').first().clone();
var nativelang_name = initialn_row.find('td:eq(0) select').attr('name'); // first td select
var nlanglevel_name = initialn_row.find('td:eq(1) select').attr('name'); // second td select
initialn_row.find('td:eq(0) select').attr('name', nativelang_name + ncount);
initialn_row.find('td:eq(1) select').attr('name', nlanglevel_name + ncount);
var nativelang_id = initialn_row.find('td:eq(0) select').attr('id'); // first td select
var nlanglevel_id = initialn_row.find('td:eq(1) select').attr('id'); // second td select
initialn_row.find('td:eq(0) select').attr('id', nativelang_id + ncount);
initialn_row.find('td:eq(1) select').attr('id', nlanglevel_id + ncount);
$('table.nativelanguages').append(initialn_row);
}
});
});
$(document).ready(function(){
$('#remBtnNative').on('click', function(e){
if($('.nativelangdrop').length > 1) {
ncount--;
var initialn_row = $('tr.initialn').last().remove();
}
});
});
var pcount = -1;
$(document).ready(function(){
$('#addBtnPract').on('click', function(e){
if($('.practlangdrop').length < 6) {
pcount++;
var initialp_row = $('tr.initialp').first().clone();
var practlang_name = initialp_row.find('td:eq(0) select').attr('name'); // first td select
var planglevel_name = initialp_row.find('td:eq(1) select').attr('name'); // second td select
initialp_row.find('td:eq(0) select').attr('name', practlang_name + pcount);
initialp_row.find('td:eq(1) select').attr('name', planglevel_name + pcount);
var practlang_id = initialp_row.find('td:eq(0) select').attr('id'); // first td select
var planglevel_id = initialp_row.find('td:eq(1) select').attr('id'); // second td select
initialp_row.find('td:eq(0) select').attr('id', practlang_id + pcount);
initialp_row.find('td:eq(1) select').attr('id', planglevel_id + pcount);
$('table.practlanguages').append(initialp_row);
}
});
});
$(document).ready(function(){
$('#remBtnPract').on('click', function(e){
if($('.practlangdrop').length > 1) {
pcount--;
var initialp_row = $('tr.initialp').last().remove();
}
});
});
PHP:
if(isset($_POST["u"])){
include_once("php_includes/db_conx.php");
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
$ct = $_POST['ct'];
$nl = preg_replace('#[^a-z]#', '', $_POST['nl']);
$nll = preg_replace('#[^a-z]#', '', $_POST['nll']);
$nl0 = preg_replace('#[^a-z]#', '', $_POST['nl0']);
$nll0 = preg_replace('#[^a-z]#', '', $_POST['nll0']);
$nl1 = preg_replace('#[^a-z]#', '', $_POST['nl1']);
$nll1 = preg_replace('#[^a-z]#', '', $_POST['nll1']);
$nl2 = preg_replace('#[^a-z]#', '', $_POST['nl2']);
$nll2 = preg_replace('#[^a-z]#', '', $_POST['nll2']);
$pl = preg_replace('#[^a-z]#', '', $_POST['pl']);
$pll = preg_replace('#[^a-z]#', '', $_POST['pll']);
$pl0 = preg_replace('#[^a-z]#', '', $_POST['pl0']);
$pll0 = preg_replace('#[^a-z]#', '', $_POST['pll0']);
$pl1 = preg_replace('#[^a-z]#', '', $_POST['pl1']);
$pll1 = preg_replace('#[^a-z]#', '', $_POST['pll1']);
$pl2 = preg_replace('#[^a-z]#', '', $_POST['pl2']);
$pll2 = preg_replace('#[^a-z]#', '', $_POST['pll2']);
$pl3 = preg_replace('#[^a-z]#', '', $_POST['pl3']);
$pll3 = preg_replace('#[^a-z]#', '', $_POST['pll3']);
$pl4 = preg_replace('#[^a-z]#', '', $_POST['pl4']);
$pll4 = preg_replace('#[^a-z]#', '', $_POST['pll4']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
if($u == "" || $e == "" || $p == "" || $g == "" || $c == "" || $ct == "" || $nl == "" || $pl == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 25) {
echo "Username must be between 3 and 25 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
$p_hash = md5($p);
$sql = "INSERT INTO users (username, email, password, gender, country, city, nativelang, nlanglevel, nativelang0, nlanglevel0, nativelang1, nlanglevel1, nativelang2, nlanglevel2, practlang, planglevel, practlang0, planglevel0, practlang1, planglevel1, practlang2, planglevel2, practlang3, planglevel3, practlang4, planglevel4, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ct','$nl','$nll','$nl0','$nll0','$nl1','$nll1','$nl2','$nll2','$pl','$pll','$pl0','$pll0','$pl1','$pll1','$pl2','$pll2','$pl3','$pll3','$pl4','$pll4','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
$to = "$e";
$from = "email#site.com";
$subject = 'blah | Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title> Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;">Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
HTML:
<legend class="legend"><h3>Select your languages</h3></legend>
<ul class="list-unstyled">
<li>
<div class="lala">
<table class="nativelanguages">
<tr>
<td>Spoken language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialn">
<td>
<select class="nativelangdrop" id="nativelang" name="nativelang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select></td>
<td>
<select class="langleveldrop" id="nlanglevel" name="nlanglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnNative">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnNative">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
<div class="lala">
<table style="float:left; margin-top:20px;" id="plang" class="practlanguages">
<tr>
<td>Practicing language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialp">
<td>
<select class="practlangdrop" id="practlang" name="practlang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
<td><select class="langleveldrop" id="planglevel" name="planglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnPract">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnPract">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
</li>
</ul>
Where you get your element values, try changing them to like this:
var u = _("username").value ? _("username").value : '';
This uses a Ternary Operator to set the value of u.
The syntax is: condition ? result-if-True : result-if-False;
Basically, this says, if _("username").value returns a value, assign that value to u, if not, set the value of u to "" (an empty string)
Below is a contrived example using regular jQuery method $("#username").val() I imagine it will also work with _("username").value though Im not sure what the benefit of doing _("username").value is having never seen this before myself.
var u = $("#username").val() ? $("#username").val() : 'not found';
alert(u);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I suggest to use chrome developer tools so you can see what jquery.ajax send
https://developer.chrome.com/devtools#improving-network-performance
in php, you can see what are incoming using
print_r($_POST)
and
print_r($_GET)

How to push data from database and see vote count after each data?

What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
On a different php file:
require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$connection = mysqli_connect('localhost', 'root', '', 'alsp');
$sql = mysqli_query($connection,"SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: start-quiz.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your username and submit</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<button class="btn btn-action" type="submit" value="finish">Submit</button>
</form>';
exit();
}
$singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()"class="btn btn-action">Submit</button></span>';
echo $output;
}
}
I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.

Javascript PhP mailing Doesnt work in new project

I am trying to integrate an old mailing script I have from a past project to my new site. The process involves a javascript and a php script in the following manner.
<script type="text/javascript">
function send_mail() {
var subject = document.getElementById('subject').value;
var message = document.instanceById('message').getContent();
var params = 'subject='+subject+'&message='+message;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else { xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); }
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById('result').innerHTML=xmlhttp.responseText; }
}
document.getElementById('result').innerHTML = 'Message is sending.. please wait..';
xmlhttp.open('POST', 'scripts/newsletter-mail.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
The form :
<label><strong>Title</strong></label>
<input type="text" name="subject" id="subject" class="form-control" value="">
<br>
</div>
<div class="col-md-12">
<label><strong>Main Text</strong></label>
<textarea class="summernote" id="text" name="message" id="message" data-plugin-summernote data-plugin-options='{ "height": 300, "codemirror": { "theme": "ambiance" } }'></textarea>
<input class="button" type="submit" id="submit" name="submit" value="Send Email" onclick="send_mail();" />
An the php script
#error_reporting(E_ALL & ~E_NOTICE);
session_cache_limiter('nocache, must-revalidate');
session_start();
include_once '../../scripts/mysql.lib.php';
$mysql = new mysql(TRUE);
$serv = $mysql->fetch("SELECT * FROM server ;", FALSE);
$host = $serv['host'];
$limit = 100;
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers[] = 'From: My Address';
$headers[] = 'X-Priority: 5';
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: text/html; charset="utf-8"' . "\r\n";
$hlist = implode("\r\n", $headers);
$result = 1;
$list = $mysql->fetch('SELECT COUNT(*) AS count FROM newsletter;', FALSE);
$count = $list['count'];
$emails = $mysql->fetch("SELECT email_id, email FROM newsletter WHERE status = 'none' LIMIT $limit;", TRUE);
if ($mysql->num_rows > 0) {
$sent = array();
$error = array();
foreach($emails as $email) {
$msg = $message . "\r\n<br /><br />" . '<small>If you wish to unregister from our newsletter list please click Here</small>';
if (#mail($email['email'], $subject, $msg, $hlist)) { $sent[] = $email['email_id']; }
else { $error[] = $email['email_id']; }
unset($msg);
}
$updsent = $mysql->query("UPDATE newsletter SET status = 'sent' WHERE email_id IN('" . implode("','",$sent) . "');");
$upderror = $mysql->query("UPDATE newsletter SET status = 'error' WHERE email_id IN('" . implode("','",$error) . "');");
switch(TRUE) {
case (count($error) == 0): $result = 3; break;
case (count($error) == $mysql->num_rows): $result = 4; break;
case (count($error) > 0): $result = 5; break;
}
}
if (($result == 1) && ($count > 0)) { $result = 2; }
switch($result) {
case 1: echo 'No Email Address in List - Message was not sent.'; break;
case 2: echo 'All User have received the Message'; break;
case 3: echo 'Message Sent!<br />(Cont. Sending ..)'; break;
case 4: echo 'Error - Message was not sent.'; break;
case 5: echo 'Message Sent to some User.<br />(Cont. Sending..)'; break;
}
?>
In the Html above the form there exist a div to grab results.
In short, after migrating the code to my project, nothing works what so ever. Nothing is sent, no result appear in the result div and my URL bar gets back the following:
newsletter-mail.php?subject=This is a title &message=<p>This is a test message<%2Fp>&submit=Send+Email
Any ideas will be appreciated.

Mandatory fields in php contact form using javascript

I need to make this form mandatory for the following fields.
Name:
Mobile Phone
Email Address:
Address Line 1:
Address Line 2:
City/Town:
County:
Postcode:
Service Requested Problem:
Item/PC Model Number:
Device Type:
Invoice Number:
I have tried using JavaScript by placing it in the header and in the index file but cant see to get either of them to work. Any ideas or suggestions would be much appreciated. I don't want to use PHP or have to re-code the current contact form.
PHP:
<?php
if (array_key_exists('func',$_REQUEST)) {
$func = $_REQUEST['func'];
} else {
$func = "";
}
function submitsq() {
require_once("header.php");
require_once("deps.php");
$rs_connect = #mysql_connect($dbhost, $dbuname, $dbpass) or die("Couldn't connect the db");
$rs_select_db = #mysql_select_db($dbname, $rs_connect) or die("Couldn't select the db");
mysql_query("SET NAMES utf8");
require_once("common.php");
if (array_key_exists('sent',$_REQUEST)) {
$sent = pv($_REQUEST['sent']);
if($sent == 1) {
echo "<br><div class=noticebox><font class=text16b>".pcrtlang("Thank You for contacting us. We will contact you as soon as possible").".<br><br>";
echo pcrtlang("If you have any other Service Requests, you may submit them below").".";
echo "</font></div><br>";
} else {
echo "<br><div class=noticebox><font class=text16b>".pcrtlang("Service Request Not Sent").".<br><br>";
echo "</font></div><br>";
}
}
$sreq_ip = $_SERVER['REMOTE_ADDR'];
$rs_chkip = "SELECT * FROM servicerequests WHERE sreq_ip = '$sreq_ip' AND sreq_datetime > (DATE_SUB(NOW(),INTERVAL $withindays DAY))";
$rs_result = mysql_query($rs_chkip, $rs_connect);
$totalsubs = mysql_num_rows($rs_result);
if($totalsubs < $maxcount) {
echo "<br><div class=box><font class=text16b>".pcrtlang("Submit Service Requests")."</font><br><br>";
echo "<form action=index.php?func=submitsq2 method=post name=myform>";
echo "<table style=\"width:100%;\"><tr><td style=\"vertical-align:top;width:50%;\"\"><table>";
echo "<tr><td><font class=text14>".pcrtlang("Your Name").":</font></td><td><input name size=26 required type=text name=sreq_name onFocus=\"this.form.submitbutton.disabled=false;this.form.submitbutton.value='".pcrtlang("Submit Service Request")."';\"></td></tr>";
echo "<tr><td><font class=text14>".pcrtlang("Company").":</font></td><td><input size=26 type=text name=sreq_company></td></tr>";
echo "<tr><td colspan=2><font class=text10i><br>".pcrtlang("Please enter at least one phone number").".</font></td></tr>";
echo "<tr><td><font class=text14>".pcrtlang("Home Phone Number").":</font></td><td><input size=18 type=text name=sreq_phone></td></tr>";
echo "<tr><td><font class=text14>".pcrtlang("Mobile Phone Number").":</font></td><td><input size=18 type=text name=sreq_cellphone></td></tr>";
echo "<tr><td><font class=text14>".pcrtlang("Work Phone Number").":</font></td><td><input size=18 type=text name=sreq_workphone></td></tr>";
echo "<tr><td><font class=text14>".pcrtlang("Email Address").":</font></td><td><input size=18 type=text name=sreq_email></td></tr>";
echo "<tr><td><font class=text14>$pcrt_address1:</font></td><td><input size=24 type=text name=sreq_addy1></td></tr>";
echo "<tr><td><font class=text14>$pcrt_address2:</font></td><td><input size=24 type=text name=sreq_addy2></td></tr>";
echo "<tr><td><font class=text14>$pcrt_city:</font></td><td><input size=18 type=text name=sreq_city></td></tr>";
echo "<tr><td><font class=text14>$pcrt_state:</font></td><td><input size=6 type=text name=sreq_state></td></tr>";
echo "<tr><td><font class=text14>$pcrt_zip:</font></td><td><input size=10 type=text name=sreq_zip></td></tr>";
echo "</table></td><td> </td><td style=\"vertical-align:top\">";
echo "<font class=text14>".pcrtlang("Service Requested/Problem").":</font><br><textarea name=sreq_problem requires cols=40 rows=10 onFocus=\"this.form.submitbutton.disabled=false;this.form.submitbutton.value='".pcrtlang("Submit Service Request")."';\"></textarea>";
echo "<br><br><font class=text14>".pcrtlang("Item / PC Model Number: ie. Dell, Apple, HP, etc")."</font><br><input size=36 type=text name=sreq_model>";
echo "<br><br><font class=text14>".pcrtlang("Device Type: ie. Laptop, PC, Tablet, etc")."</font><br><input size=36 type=text name=sreq_type>";
echo "<br><br><font class=text14>".pcrtlang("Invoice Number")."</font><br><input size=36 type=text name=sreq_pcid>";
if($allowusertochoosestore == "yes") {
echo "<br><br><font class=text14>".pcrtlang("Preferred Store/Location").":</font><br><select name=storeid>";
echo "<option selected value=\"0\">".pcrtlang("No Preference")."</option>";
$rs_ql = "SELECT * FROM stores WHERE storeenabled = '1'";
$rs_result1 = mysql_query($rs_ql, $rs_connect);
while($rs_result_q1 = mysql_fetch_object($rs_result1)) {
$storeid = "$rs_result_q1->storeid";
$storename = "$rs_result_q1->storename";
$storesname = "$rs_result_q1->storesname";
echo "<option value=\"$storeid\">$storename - <$storesname></option>";
}
echo "</select>";
} else {
echo "<input type=hidden name=storeid value=0>";
}
echo "</select><br>";
if($recaptcha_enable == "yes") {
echo "<br><br><font class=text14>".pcrtlang("Please enter the words below").":</font><br>";
require_once('recaptchalib.php');
echo recaptcha_get_html($recaptcha_public_key);
echo "<font class=text10>".pcrtlang("This little test is just to make sure you are a real person and not a spammer so that our oncall technician only receives mobile phone notifications for genuine service requests").".</font>";
}
echo "<br><br><input class=button id=submitbutton type=submit value=\"".pcrtlang("Submit Service Request")."\" onclick=\"this.disabled=true;this.value='".pcrtlang("Sending Request")."...'; this.form.submit();\">";
echo "</td></tr></table></div></form>";
} else {
echo "<br><div class=noticebox><font class=text16b>".pcrtlang("Sorry, the maximum number of requests has been reached").".<br><br>";
echo "</font></div><br>";
}
require_once("footer.php");
}
function submitsq2() {
require("deps.php");
$rs_connect = #mysql_connect($dbhost, $dbuname, $dbpass) or die("Couldn't connect the db");
$rs_select_db = #mysql_select_db($dbname, $rs_connect) or die("Couldn't select the db");
mysql_query("SET NAMES utf8");
require("common.php");
if (function_exists('date_default_timezone_set')) {
date_default_timezone_set("$pcrt_timezone");
}
$currentdatetime = date('Y-m-d H:i:s');
$sreq_name = pv($_REQUEST['sreq_name']);
$sreq_company = pv($_REQUEST['sreq_company']);
$sreq_phone = pv($_REQUEST['sreq_phone']);
$sreq_cellphone = pv($_REQUEST['sreq_cellphone']);
$sreq_workphone = pv($_REQUEST['sreq_workphone']);
$sreq_model = pv($_REQUEST['sreq_model']);
$sreq_type = pv($_REQUEST['sreq_type']);
$sreq_email = pv($_REQUEST['sreq_email']);
$sreq_addy1 = pv($_REQUEST['sreq_addy1']);
$sreq_addy2 = pv($_REQUEST['sreq_addy2']);
$sreq_city = pv($_REQUEST['sreq_city']);
$sreq_state = pv($_REQUEST['sreq_state']);
$sreq_zip = pv($_REQUEST['sreq_zip']);
$sreq_problem = pv($_REQUEST['sreq_problem']);
$sreq_storeid = pv($_REQUEST['storeid']);
$sreq_custsourceid = pv($_REQUEST['custsourceid']);
$sreq_pcid = pv($_REQUEST['sreq_pcid']);
$sreq_ip = $_SERVER['REMOTE_ADDR'];
$sreq_agent = $_SERVER['HTTP_USER_AGENT'];
if($recaptcha_enable == "yes") {
require_once('recaptchalib.php');
$resp = recaptcha_check_answer ($recaptcha_private_key,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die (pcrtlang("The words in the puzzle were not entered correctly. Please go back and try it again."));
} else {
// Your code here to handle a successful verification
}
}
$rs_chkip = "SELECT * FROM servicerequests WHERE sreq_ip = '$sreq_ip' AND sreq_datetime > (DATE_SUB(NOW(),INTERVAL $withindays DAY))";
$rs_result = mysql_query($rs_chkip, $rs_connect);
$totalsubs = mysql_num_rows($rs_result);
if($totalsubs >= $maxcount) {
header("Location: index.php?sent=0");
} else {
$rs_insert_sq = "INSERT INTO servicerequests (sreq_ip,sreq_agent,sreq_name,sreq_company,sreq_homephone,sreq_cellphone,sreq_workphone,sreq_addy1,sreq_addy2,sreq_city,sreq_state,sreq_zip,sreq_email,sreq_problem,sreq_model,sreq_datetime,storeid,sreq_custsourceid,sreq_pcid) VALUES ('$sreq_ip','$sreq_agent','$sreq_name','$sreq_company','$sreq_phone','$sreq_cellphone','$sreq_workphone','$sreq_addy1','$sreq_addy2','$sreq_city','$sreq_state','$sreq_zip','$sreq_email','$sreq_problem','$sreq_model $sreq_type','$currentdatetime','$sreq_storeid','$sreq_custsourceid','$sreq_pcid')";
#mysql_query($rs_insert_sq, $rs_connect);
if ($sreq_storeid != "0") {
$rs_qstores = "SELECT * FROM stores WHERE storeid = '$sreq_storeid'";
$rs_result1 = mysql_query($rs_qstores, $rs_connect);
$rrow = mysql_fetch_array($rs_result1);
$oncalluser = $rrow['oncalluser'];
} else {
$rs_qstoresid = "SELECT * FROM stores WHERE storedefault = '1'";
$rs_result1id = mysql_query($rs_qstoresid, $rs_connect);
$rrow = mysql_fetch_array($rs_result1id);
$oncallstoreid = $rrow['storeid'];
$rs_qstores = "SELECT * FROM stores WHERE storeid = '$oncallstoreid'";
$rs_result1 = mysql_query($rs_qstores, $rs_connect);
$rrow = mysql_fetch_array($rs_result1);
$oncalluser = $rrow['oncalluser'];
}
$rs_quser = "SELECT * FROM users WHERE username = '$oncalluser'";
$rs_resultuser1 = mysql_query($rs_quser, $rs_connect);
$urow = mysql_fetch_array($rs_resultuser1);
$useremail = $urow['useremail'];
$usermobile = $urow['usermobile'];
if(($useremail != "") && ($oncallsendemail == "yes")) {
require_once("sendenotify.php");
$from = "$useremail";
$to = "$useremail";
$subject = pcrtlang("Service Request Submitted");
$plaintext ="$sreq_name\n$sreq_company\n$sreq_addy1\n$sreq_addy2\n$sreq_city, $sreq_state $sreq_zip\n\n".pcrtlang("Home Phone").":\t$sreq_phone\n".pcrtlang("Cell Phone").":\t$sreq_cellphone\n".pcrtlang("Work Phone").":\t$sreq_workphone";
$plaintext .= "\n\n".pcrtlang("Email").": $sreq_email\n\n".pcrtlang("Device").": $sreq_model $sreq_type\n\n".pcrtlang("Problem").":\n$sreq_problem\n";
$sreq_problem2 = nl2br($_REQUEST['sreq_problem']);
$htmltext ="<b>$sreq_name</b><br>$sreq_name<br>$sreq_addy1<br>$sreq_addy2<br>$sreq_city, $sreq_state $sreq_zip<br><br><b>".pcrtlang("Home Phone").":</b>$sreq_phone<br><b>".pcrtlang("Cell Phone").":</b>$sreq_cellphone<br><b>".pcrtlang("Work Phone").":</b>$sreq_workphone";
$htmltext .= "<br><br><b>".pcrtlang("Email")."</b>:$sreq_email<br><br><b>".pcrtlang("Device").":</b> $sreq_model $sreq_type<br><br><b>".pcrtlang("Problem").":</b><br>$sreq_problem2<br><br>";
sendenotify("$from","$to","$subject","$plaintext","$htmltext");
}
if(($usermobile != "") && ($oncallsendsms == "yes")) {
require_once("smsnotify.php");
$smsname = urlencode("$sreq_name");
$sms_cellphone = urlencode("$sreq_cellphone");
smssend("$usermobile",pcrtlang("A Service Request has been submitted by")." $smsname - $sms_cellphone.");
}
header("Location: index.php?sent=1");
}
}
switch($func) {
default:
submitsq();
break;
case "submitsq2":
submitsq2();
break;
}
?>
JavaScript:
<script language="javascript"
type="text/javascript">
<!-- hide script from older browsers
function validateForm(myform)
{
if(""==document.forms.myform.sreq_name.value)
{
alert("Please enter your full name.");
return false;
}
if(""==document.forms.myform.sreq_cellphone.value)
{
alert("Please enter your email address.");
return false;
}
if(""==document.forms.contact.sreq_phone.value)
{
alert("Please enter your phone number.");
return false;
}
}
stop hiding script -->
</script>
Corrections to your script
<script type="text/javascript">
function validateForm(myform) {
var ele = myform.elements
if("" == ele['sreq_name'].value) {
alert("Please enter your full name.");
return false;
}
if("" == ele['sreq_cellphone'].value ) {
alert("Please enter your email address.");
return false;
}
if("" == ele['contact.sreq_phone'].value) {
alert("Please enter your phone number.");
return false;
}
}
</script>
If the are any errors in your function then the form is automatically submitted without validation.
You also need to do validation on the server-side.

Categories