Mandatory fields in php contact form using javascript - 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.

Related

getting unexpected output from ajax

I am creating wishlist where I am sending data via ajax but it's not returning data as I implemented in the code I fail to figure out what is the main reason behind this. Here is the code
<li><span><i style="color:red;" class="<?php
if(isset($_SESSION['email'])){
$selwishlist = $con->prepare("SELECT * FROM wishlist WHERE user_id =:userid and product_id =:productid ");
$selwishlist->bindParam(":userid",$userid);
$selwishlist->bindParam(":productid",$id);
$selwishlist->execute();
$selresultwishlis = $selwishlist->rowCount();
if($selresultwishlis > 0){
echo "fa fa-heart";}else{
echo "ion-android-favorite-outline";
}}else{
echo "ion-android-favorite-outline";
}
?> wishlist-click" id="wishlist-product-id-<?php echo $id; ?>"></i></span>
</li>
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
$userdetail = $con->prepare("SELECT * FROM user WHERE email = :email");
$userdetail->bindParam(":email",$email);
$userdetail->execute();
$userres = $userdetail->fetch();
$userid = $userres['id'];
}
else{
$email = '';
$userid = '';
}
This is my input button Where first I check if the session is running or not an then check if the item is in the user wishlist or not and according to that I change the class of wishlist icon
$(".wishlist-click").click(function(e){
e.preventDefault();
var el = $(this);
alert('I am clicked')
var ids = this.id;
var splitids = ids.split('-');
var wishlistid = splitids[3];
$.ajax({
url:'wishlistajax.php',
type:'POST',
data:{ids:wishlistid},
success:function(response){
if(response == 1){
alert('1');
}else if(response == '0'){
alert('0');
}else if(response == '3'){
alert('its 3');
}
else{
alert('Not in All');
}
}
});
});
This is my jquery code and I am getting Not in both in response AND HERE IS MY AJAX CODE
<?php
session_start();
if(isset($_SESSION['email'])){
echo "1";
exit();
if(isset($_POST['ids'])){
$email = $_SESSION['email'];
$productid = htmlspecialchars($_POST['ids']);
include "conn.php";
$userdetail = $con->prepare("SELECT * FROM user WHERE email = :email");
$userdetail->bindParam(":email",$email);
$userdetail->execute();
$userres = $userdetail->fetch();
$userid = $userres['id'];
$ip = $_SERVER['REMOTE_ADDR'];
$insertquery = $con->prepare("INSERT INTO wishlist (product_id, user_id) VALUES (:productid, :userid)");
$insertquery->bindParam(":productid",$productid);
$insertquery->bindParam(":userid",$userid);
$insertquery->execute();
echo 'Item added';
exit();
}}
else{
echo '2';
header("location:loginregister.php");
exit();
}
echo '3';
exit();
?>

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.

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

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.

Registration form email verification [closed]

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.

Categories