My whole signup page code is here.
Link
I'm trying to add this dynamic fields to the signup page code.
<script>
var i = 1;
function addKid(){
if (i <= 6){
i++;
var div = document.createElement('div');
div.style.width = "44%";
div.style.height = "26px";
div.style.color = "white";
div.setAttribute('class', 'myclass');
div.innerHTML = 'Child : <input type="text" name="child_'+i+'" > Ages : <input type="text" name="ages_'+i+'"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';
document.getElementById('kids').appendChild(div);
}
}
function removeKid(div) {
document.getElementById('kids').removeChild( div.parentNode );
i--; }
<div id="kids">
Child : <input id="child_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="50">
Ages : <input id="ages_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="10"><input type="button" id="add_kid()" onClick="addKid()" value="+" />
</div>
I can get the "child_1 / chi" and "ages_1 / ags" insert into my database. no problem.
When I try to create a extra dynamic field in my signup, "child_2 and ages_2".....
then I can't get that info from "child_2 and ages_2" insert into my database.
Can some one tell me what I'm doing wrong since I can't get that info into my database.? Am I suppose to call "child_2 / chi2" and "ages_2 / ags2" for something els before it will work.?
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.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']);
$chi = preg_replace('#[^a-z.,-/ ]#i', '', $_POST['chi']);
$ags = preg_replace('#[^0-9.]#i', '', $_POST['ags']);
$chi2 = preg_replace('#[^a-z.,-/ ]#i', '', $_POST['chi2']);
$ags2 = preg_replace('#[^0-9.]#i', '', $_POST['ags2']);
$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 == "" || $chi == "" || $ags == "" || $chi2 == "" || $ags2 == "" || $c == ""){
..
$sql = "INSERT INTO users (username, email, password, gender, child_1, ages_1, child_2, ages_2, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$chi','$ags','$chi2','$ags2','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
..
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
} else if(elem == "child_1"){
rx = /[^a-z.,-/ ]/gi;
} else if(elem == "ages_1"){
rx = /[^0-9.]/gi;
} else if(elem == "child_2"){
rx = /[^a-z.,-/ ]/gi;
} else if(elem == "ages_2"){
rx = /[^0-9.]/gi;
}
tf.value = tf.value.replace(rx, "");
}
..
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var chi = _("child_1").value;
var ags = _("ages_1").value;
var chi2 = _("child_2").value;
var ags2 = _("ages_2").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || chi == "" || ags == "" || chi2 == "" || ags2 == "" || g == ""){
..
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&chi="+chi+"&ags="+ags+"&chi2="+chi2+"&ags2="+ags2+"&g="+g);
}
..
kindly save your child and age in array and pass it in ajax. so that you can loop the child and age as given below and insert it into table.
For password and conform password use js. and validate it in front end itself. save password alone in table that's enough.
try to understand this code and do alterations as required. but i sloved your dynamic child and age problem. run this code
page1.php
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</script></script>
<script type="text/javascript">
$(document).ready(function(){
$("#input_form").submit(function(){
var querystring = $(this).serialize();
$.ajax({
url: 'save_child.php',
type: "POST",
data: querystring,
success: function(data) {
alert("jhkl");
}
});
//$('#result').html(querystring);
return false;
});
});
</script>
<title>Serialize</title>
</head>
<body>
<form id="input_form">
first name: <input type="text" name="username" id="first name"/><br />
password: <input type="text" name="password" id="last name"/><br />
email: <input type="text" name="email" id="email"/><br />
<div id="kids">
Child : <input id="child_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="50" name="child[]">
Ages : <input id="ages_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="10" name="ages[]"><input type="button" id="add_kid()" onClick="addKid()" value="+" />
</div>
<input type="submit" value="send" name="submit" />
</form>
<p id="result"></p>
</body>
</html><script>
var i = 1;
function addKid(){
if (i <= 5){
i++;
var div = document.createElement('div');
div.style.width = "44%";
div.style.height = "26px";
div.style.color = "white";
div.setAttribute('class', 'myclass');
div.innerHTML = 'Child : <input type="text" name="child[]" > Ages : <input type="text" name="ages[]"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';
document.getElementById('kids').appendChild(div);
}
}
function removeKid(div) {
document.getElementById('kids').removeChild( div.parentNode );
i--; }
</script>
save_child.php
<?php
$child=$_REQUEST['child'];// child array
$ages=$_REQUEST['ages'];
$InputArray = array();
$conn=mysqli_connect("localhost","root","","tes");// data base connection
$InputArray['username']=$_REQUEST['username'];// get datas and store in a array named InputArray
$InputArray['password']=$_REQUEST['password'];
$InputArray['email']=$_REQUEST['email'];
$i=1;
foreach($child as $val){
$b=$i-1;
$InputArray['child_'.$i]=$val;
$InputArray['age_'.$i]=$ages[$b];
$i++;
}
$sql="CREATE TABLE IF NOT EXISTS `userss` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`email` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`country` varchar(20) NOT NULL,
`child_1` varchar(20) NOT NULL,
`age_1` varchar(20) NOT NULL,
`child_2` varchar(20) NOT NULL,
`age_2` varchar(20) NOT NULL,
`child_3` varchar(20) NOT NULL,
`age_3` varchar(20) NOT NULL,
`child_4` varchar(20) NOT NULL,
`age_4` varchar(20) NOT NULL,
`child_5` varchar(20) NOT NULL,
`age_5` varchar(20) NOT NULL,
`ip` varchar(60) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ";
mysqli_query($conn,$sql);
if (count($InputArray) > 0) {
while (list($key, $val) = each($InputArray)) {
if(!empty($val)){
$fields.= $key . ',';
$valset.= "'". $val ."',";
}
}
}
$fields = trim($fields, ',');
$valset = trim($valset, ',');
$sql = "INSERT INTO userss ($fields) VALUES ($valset)";
mysqli_query($conn,$sql);
?>
Another one thing I have noted in your code.
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
you have written two query for this. make it single as given
$sql = "SELECT id FROM users WHERE email='$e' and username='$u' LIMIT 1";
Related
I want to prevent send data to database when user use numbers in the username input for example. I used event.prevent Default() for that, but not working.(also return false) what should I do?
My code:
PHP:
if (!empty($shomare) && !empty($pass) && !empty($first) && !empty($last)) {
$connection = mysqli_connect('localhost', 'root', '', 'portal');
$sql = " INSERT INTO students (shomare,pass,first,last,major,birth) VALUES ('$shomare','$hashpass','$first','$last','$major','$birth') ;";
mysqli_query($connection, $sql); header('location: dashboard.php');
}
HTML:
<input type="text" name="shomare" id="shomare" onblur="check1();" style="margin-left: 5px;width: 200px;">
<br>
<div id="shomare1"></div>
JavaScript:
function check1() {
const shomare = document.getElementById('shomare');
if (!/^\d+$/.test(shomare.value)) {
document.getElementById('shomare1').innerHTML = '<a style="font-size: 15px;color: dimgrey;">!کد دانشجویی فقط شامل اعداد می باشد</a>';
return false;
}
if (shomare.value.length != 8) {
document.getElementById('shomare1').innerHTML = '<a style="font-size: 15px;color: dimgrey;">!کد دانشجویی باید 8 رقمی باشد</a>';
return false;
}
if( /^\d+$/.test(shomare.value) && shomare.value.length == 8 ) {
document.getElementById('shomare1').innerHTML = '';
}
}
I am looking to create a contact Us form in my website, where after the form is submitted, the text fields should be cleared, and a Thank You should appear.
Here is the html code :
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<form action="contactform.php" method="post" role="form" class="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name (eg: James)" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email (eg: james#example.com)" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Phone Number (eg: 0406 624 456)" data-rule="minlen:9" data-msg="Please enter a valid contact number" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<br/>
<div class="text-center">
<button type="submit" name="submit" value="Submit"></button>
<!--b>Send Message</b-->
</div>
</form>
The relevant java script code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function(){
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
case 'email':
if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
break;
case 'checked':
if( !i.attr('checked') ){ ferror=ierror=true; }
break;
case 'regexp':
exp = new RegExp(exp);
if( !exp.test(i.val()) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
f.children('textarea').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
if( ferror ) return false;
else var str = $(this).serialize();
$.ajax({
// alert("enterd the loop")
type: "POST",
url: "contactform/contactform.php",
data: str,
success: function(msg){
//alert(msg);
if(msg == "New record created successfully") {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
document.getElementsByClassName("contactForm").reset();
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
Relevant php script to obtain db credentials and properties:
<?php include "../../inc/dbinfo.inc"; ?>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$Phone = test_input($_POST["Phone"]);
$message = test_input($_POST["message"]);
$submit = test_input($_POST["Submit"])
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO contact_details (name, email, Phone, message)
VALUES ('$name', '$email', '$Phone', '$message')";
// <script>alert("your message is sent successfully");
// window.location="index.html";
// </script>
if ($connection->query($sql) === TRUE) {
echo "New record created successfully";
mysqli_free_result($result);
mysqli_close($connection);
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
mysqli_free_result($result);
mysqli_close($connection);
}
?>
after submitting the form, the form doesn't reset and displays any message but its getting updated in the database.
Redirect to new page or same page like below:
if ($connection->query($sql) === TRUE) {
mysqli_free_result($result);
mysqli_close($connection);
header('Location: filename?msg=success');
}
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)
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.
I am having a lot of trouble with form values, first I echoed out the MYSQL insert function to see what data was attempting to be put into the database and for one MYSQL insert function it was replacing most of my entered data into '' so first I thought it was my preg_replace function in the PHP part of my code but I removed this and the same thing was still happening, I am now not sure where it has gone wrong but I am guessing somewhere between the Javascript and the form. I really am lost on where to turn now. The INSERT function for the User table works perfectly fine it picks up all the entered data but with this Member table it is a different story
Javascript
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem === "email"){
rx = /[' "]/gi;
} else if(elem === "username"){
rx = /[^a-z0-9]/gi;
} else if(elem === "mobileNumber"){
rx = /[^0-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 m = _("mobileNumber").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var ci = _("city").value;
var pc = _("postcode").value;
var c = _("country").value;
var d = _("dateOfBirth").value;
var g = _("gender").value;
var ln = _("lastName").value;
var fn = _("firstName").value;
var status = _("status");
if(u === "" || e === "" || p1 === "" || p2 === "" || c === ""
|| g === "" || m === "" || ci === "" || pc === "" || d === "" ){
status.innerHTML = "Fill out required fields";
} else if(p1 !== p2){
status.innerHTML = "Your password fields do not match";
}else if(m.value !== 11 && isNaN(m)){
status.innerHTML = "Please enter valid mobile number";
}else if(d === "dd/mm/yyyy"){
status.innerHTML = "Please enter your date of birth";
} else {
//ajax to send form data to php
//hides sign button
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//wait until php verifies data
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) === true) {
//if sign not succesful unhide button
if(ajax.responseText !== "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+"";
}
}
};
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ci"+ci+"&m"+m+"&pc"+pc+"&d"+d);
}
}
Form
<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="email" 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>First name:</div>
<input id="firstName" type="text" /><br />
<div>Last name:</div>
<input id="lastName" type="text" /><br />
<div>Mobile number*:</div>
<input id="mobileNumber" onfocus="emptyElement('status')" onkeyup="restrict('mobileNumber')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("country_list.php"); ?>
</select>
<div>City:</div>
<input id="city" onfocus="emptyElement('status')">
<div>Postcode:</div>
<input id="postcode" onfocus="emptyElement('status')">
<div>Relationship Status*:</div>
<select id="relationshipStatus" >
<option value=""></option>
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
<div>Date of Birth*:</div>
<input id="dateOfBirth" type="text" onfocus="emptyElement('status')">
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
INSERT functions
$sql = "INSERT INTO Member (`firstName`, `lastName`, `gender`, `emailAddress`,
`city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`, `dateOfBirth`)
VALUES('$fn', '$ln', '$g', '$e', '$ci', '$c', '$pc', '$rs', '$m', '$d')";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO User (`Userid`, `username`, `password`, `accountType`) VALUES ('$uid','$u','$p','$accountType')";
$query = mysqli_query($db_conx, $sql);