I am learning to create a social ntwk. I hv used an AJAX framework for the signup page and it wked. Now I am trying to use the same framewk for the start page . Its nt wking. The problems are with the gender conditionals. The submit button does nt click.Hw cn I fix this code so that form submits whn user is either male or female
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$gender = $row["gender"];
}
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["f"])){
// CONNECT TO THE DATABASE
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$f = preg_replace('#[^a-z0-9]#i', '', $_POST['f']);
$l = preg_replace('#[^a-z0-9]#i', '', $_POST['l']);
$wt= preg_replace('#[^a-z ]#i', '', $_POST['wt']);
$a= preg_replace('#[^a-z ]#i', '', $_POST['a']);
$ws= preg_replace('#[^a-z ]#i', '', $_POST['ws']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// FORM DATA ERROR HANDLING
if($f == "" || $l == "" || $wt || $a == "" || $ws || $c == "" ){
echo "The form submission is missing values.";
exit();
} else {
// Add user info into the database table for the main site table
$sql = "UPDATE users SET firstname='$f', lastname ='$l', wagsbooty ='$wt', abs ='$a', wagsboobs ='$ws', crash ='$c' WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
echo "startup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<style type="text/css">
#startupform{
margin-top:24px;
}
#startupform > div {
margin-top: 12px;
}
#startupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#startupbtn {
font-size:18px;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function startup(){
var f = _("firstname").value;
var l = _("lastname").value;
var wt = _("wagsbooty").value;
var a = _("abs").value;
var ws = _("wagsboobs").value;
var c = _("crash").value;
var status = _("status");
if(f == "" || l == "" wt || a == "" || ws || c == "" ){
status.innerHTML = "Fill out all of the form data";
} else {
_("startupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "start_page1.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "startup_success"){
status.innerHTML = ajax.responseText;
_("startupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("startupform").innerHTML = "OK!";
}
}
}
ajax.send("f="+f+"&l="+l+"&wt="+wt+"&a="+a+"&ws="+ws+"&c="+c);
}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<h3>Fill in this form to create your profile!</h3>
<form name="startupform" id="startupform" onsubmit="return false;">
<div>Firstname: </div>
<input id="firstname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>Lastname: </div>
<input id="lastname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest booty :";?></br>
<select id="wagsbooty" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_wags_list.php");
}else{
echo "Star with hottest abs:";?></br>
<select id="abs" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_abs_list.php");
}
?>
</select>
</div>
</br>
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest boobs :";?></br>
<select id="wagsboobs" onfocus = "emptyElement('status')" maxlength="255">
<?php include_once("template_boobs_list.php");
}else{
echo "I have a crash on :";?></br>
<select id="crash" onfocus ="emptyElement('status')" maxlength="255">
<?php include_once("template_crash_list.php");
}
?>
</div>
</select>
</br>
</br>
<button id="startupbtn" onclick="startup()">Create Profile</button>
<span id="status"></span>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
You don't have anywhere on the page for the user to select their gender within the page - you should add either a radio button or a select box to the page and pass that info to the startup() function.
Related
I am using the live search function for my MySQL database data.
But to go directly to the source I do not want a file or db in between and I went directly to the Active Directory itself.
The searching is working but after you searched for something like username, it gives the correct output, the data resets after 2/3 seconds. So the input type text is still filled in but it's showing all the results.
Does anyone can help me with this or can optimize the code?
INDEX.PHP
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Search</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">Live Data Search Active Directory</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
My fetch.php file with all the links to AD. Ofcourse crendentials and server are filled in and binding is working.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<div style="overflow-x:auto;">
</head>
</html>
<?php
$output = "";
$ldap_password = "<username>";
$ldap_username = "<password>";
$ldap_connection = ldap_connect("<ldapserver>");
if (FALSE === $ldap_connection){
echo "Unable to connect to the ldap server";
}
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password))
{
if (isset($_POST["query"]))
{
$search = $_POST["query"];
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*".$search.")(sAMAccountName=".$search."*)(l=*".$search."*)))";
}
else
{
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*)))";
}
$output .= '<table id="customers"><tr><th>Username</th><th>Last Name</th><th>First Name</th><th>Company</th><th>Office</th><th>Department</th><th>Mobile</th><th>Telephone</th><th>E-Mail Address</th></tr>';
$ldap_base_dn = "OU=NL,DC=global,DC=com";
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
//var_dump($entries);
//For each account returned by the search
for ($x=0; $x<$entries["count"]; $x++){
//Windows Username
$LDAP_samaccountname = "";
if (!empty($entries[$x]["samaccountname"][0])) {
$LDAP_samaccountname = $entries[$x]["samaccountname"][0];
if ($LDAP_samaccountname == "NULL"){
$LDAP_samaccountname= "";
}
} else {
//#There is no samaccountname s0 assume this is an AD contact record so generate a unique username
$LDAP_uSNCreated = $entries[$x]["usncreated"][0];
$LDAP_samaccountname= "CONTACT_" . $LDAP_uSNCreated;
}
//Last Name
$LDAP_LastName = "";
if (!empty($entries[$x]["sn"][0])) {
$LDAP_LastName = $entries[$x]["sn"][0];
if ($LDAP_LastName == "NULL"){
$LDAP_LastName = "";
}
}
//First Name
$LDAP_FirstName = "";
if (!empty($entries[$x]["givenname"][0])) {
$LDAP_FirstName = $entries[$x]["givenname"][0];
if ($LDAP_FirstName == "NULL"){
$LDAP_FirstName = "";
}
}
//Company
$LDAP_CompanyName = "";
if (!empty($entries[$x]["company"][0])) {
$LDAP_CompanyName = $entries[$x]["company"][0];
if ($LDAP_CompanyName == "NULL"){
$LDAP_CompanyName = "";
}
}
//Department
$LDAP_Department = "";
if (!empty($entries[$x]["department"][0])) {
$LDAP_Department = $entries[$x]["department"][0];
if ($LDAP_Department == "NULL"){
$LDAP_Department = "";
}
}
//Office
$LDAP_Office = "";
if (!empty($entries[$x]["l"][0])) {
$LDAP_Office = $entries[$x]["l"][0];
if ($LDAP_Office == "NULL"){
$LDAP_Office = "";
}
}
//Job Title
$LDAP_JobTitle = "";
if (!empty($entries[$x]["title"][0])) {
$LDAP_JobTitle = $entries[$x]["title"][0];
if ($LDAP_JobTitle == "NULL"){
$LDAP_JobTitle = "";
}
}
//Mobile Number
$LDAP_CellPhone = "";
if (!empty($entries[$x]["mobile"][0])) {
$LDAP_CellPhone = $entries[$x]["mobile"][0];
if ($LDAP_CellPhone == "NULL"){
$LDAP_CellPhone = "";
}
}
//Telephone Number
$LDAP_DDI = "";
if (!empty($entries[$x]["telephonenumber"][0])) {
$LDAP_DDI = $entries[$x]["telephonenumber"][0];
if ($LDAP_DDI == "NULL"){
$LDAP_DDI = "";
}
}
//Email address
$LDAP_InternetAddress = "";
if (!empty($entries[$x]["mail"][0])) {
$LDAP_InternetAddress = $entries[$x]["mail"][0];
if ($LDAP_InternetAddress == "NULL"){
$LDAP_InternetAddress = "";
}
}
$output .= '<tr><td><strong>' . $LDAP_samaccountname .'</strong></td><td>' .$LDAP_LastName.'</td><td>'.$LDAP_FirstName.'</td><td>'.$LDAP_CompanyName.'</td><td>'.$LDAP_Office.'</td><td>'.$LDAP_Department.'</td><td>'.$LDAP_CellPhone.'</td><td>'.$LDAP_DDI.'</td><td>'.$LDAP_InternetAddress.'</td></tr>';
} //END for loop
echo $output;
} //END FALSE !== $result
echo("</table>"); //close the table
}
?>
The loop is to display multiple results.
As you can see the result is good, but after 2/3 sec it resets and shows all data instead of the "sbx" value. (data is confidential so not shown, but it's corect)
Greets, Stef
Hello Guys this is sign up form. Please read this code and try to answer
I have two problems with this code
1) I am getting a warning
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\signup.php:252) in C:\xampp\htdocs\signup.php on line 295
2) When I click on Create account after filling form the button does nothing
i.e. it does not inserting values in table.
<?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_connnection.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_connection.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$n = preg_replace('#[^a-z ]#i', '', $_POST['n']);
$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']);
$s = preg_replace('#[^a-z ]#i', '', $_POST['s']);
// 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($n == "" || $u == "" || $e == "" || $n == "" || $p == "" || $g == "" || $s == ""){
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);
//$cryptpass = hash('sha1',$p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (name, username, email, password, gender, stream, ip, signup, lastlogin, notescheck)
VALUES('$n','$u','$e', '$p_hash','$g','$s','$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);
}
// Email the user their activation link
$to = "$e";
$from = "example#gmail.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename 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();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
#signupform{
margin-top:24px;
}
#signupform > div {
margin-top: 12px;
}
#signupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#signupbtn {
font-size:18px;
padding: 12px;
}
#terms {
border:#CCC 1px solid;
background: #F5F5F5;
padding: 12px;
}
</style>
<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 n = _("name").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var s = _("stream").value;
var g = _("gender").value;
var status = _("status");
if(n == "" || u == "" || e == "" || n == "" || p1 == "" || p2 == "" || s == "" || 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 != "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+"&n="+n+"&e="+e+"&n="+n+"&p="+p1+"&s="+s+"&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>Name:</div>
<input id="name" type="text" onfocus="emptyElement('status')">
<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="88">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="100">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Stream:</div>
<select id="stream" onfocus="emptyElement('status')">
<option disabled selected value>--select your option--</option>
<option value="Arts">India</option>
<option value="Biology">USA</option>
<option value="Maths">Russia</option>
</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>
</div>
</body>
</html>
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("includes/db_connection.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 || strlen($p) != 74){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
} else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}
?>
ajax.js file
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
main.js file
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
I have simple registration formulae and I want I want to firstly send with ajax and without refreshing the page to control if I insert correct data and then just redirect to some other page. The problem is that after I send it through ajax to the same page everything is working but content of my page is being duplicate, I can see it twice...
here is my ajax
function registruj () {
var name = $('#meno').val();
var priez = $('#priezvisko').val();
var log = $('#login').val();
var mail = $('#mail').val();
var cisloTel = $('#cislo').val();
var heslo = $('#heslo').val();
var heslo1 = $('#heslo1').val();
$.post( "", {
'meno': name,
'priezvisko': priez,
'login':log,
'mail':mail,
'cislo':cisloTel,
'heslo':heslo,
'heslo1':heslo1,
}, function (data) {
$('#result').html(data);
}
);
$('#nove').load(document.URL + ' #nove');
}
and this is my php file
<?php
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
}
?>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8" />
<title>blblblbl</title>
<link rel="stylesheet" type="text/css" href="./fancybox/jquery.fancybox-1.3.4.css" media="screen" />
<script src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script>$(function(){$('.img').fancybox();});</script>
<style type="text/css"> </style>
<script type="text/javascript" src="mojskript.js"></script>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/style1.css" />
</head>
<body class="registracia">
<div class="container">
<div id="nove">
<form >
<table >
<tr><td><label for="napdis">Vyplňte nasledujúci formulár:</label></td></tr>
<tr><td><input type="radio" name="pohlavie" value="zena" id="zena" >Žena</td></tr>
<br>
<tr><td><input type="radio" name="pohlavie" value="muz" id="muz">Muž</td></tr>
<br>
<tr><td><label for="meno">Meno :</label></td><td><input type = "text" id="meno" name="meno"></td></tr><br>
<tr><td><label for="priezvisko">Priezvisko :</label></td><td><input type = "text" id="priezvisko" name="priezvisko"></td></tr><br>
<tr><td><label for="login">Login :</label></td>
<td><input type = "text" id="login" name="login"></td></tr><br>
<?php
if(isset($heslo)) {
if (($heslo != "" && $hesloZnovu != "") && ($heslo == $hesloZnovu)) {
$hesloOk = 1;
}
else {
echo '<tr><td><label for="heslo">Heslo :</label><td><input type = "password" name="heslo"></td><td><label for="zleHeslo">Heslá sa nezhodujú</label></td></tr>';
$pocet = 1;
}
}
?>
<?php
if(!isset($pocet)) {
echo'<tr ><td ><label for="heslo" > Heslo :</label ></td >
<td ><input type = "password" id="heslo" name = "heslo" ></td ></tr ><br >';
}
?>
<tr><td><label for="heslo2">Heslo znovu :</label></td>
<td><input type = "password" id="heslo1" name="heslo1"></td></tr><br>
<?php
if(isset($mail)) {
if (!stristr($mail, "#") OR !stristr($mail, ".")) {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" name="email"></td><td><label for="zlyMail">Zlý formát emailu</label></td></rd></tr><br>';
} else {
$mailOk = 1;
}
}
else {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" id="mail" name="email"></td></tr><br>';
}
?>
<tr><td><label for="cislo">Telefónne číslo :</label></td>
<td><input type = "text" id="cislo" name="cislo"></td></tr><br>
<tr><td><input type="button" value="Zaregistrovať" onclick="registruj()" ></td></tr>
</table>
</form>
<?php
if(isset($mailOk) && isset($hesloOk)) {
$length = 20;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$zasifrovane = crypt($heslo,$randomString);
echo $zasifrovane;
mysql_query("INSERT INTO uzivatelia (Meno,Priezvisko,Login,Heslo,mail,pohlavie,cislo) VALUES ('$meno','$priezvisko','$login','$zasifrovane','$mail','$pohlavie','$cislo')");
header("location:index.php");
}
?>
</div>
<div id="result"></div>
</div>
</body>
How should I do that ?
Try to use exit(); like :
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
exit();
}
Use exit(); or die(); when ajax processing done otherwise it will return all page content.
Change success function to:
function (data) {
$('#result').empty().html(data);
}
When i first enter my form it calls my php function and displays the error for entering a blank. How do i stop that and only call the function when i submit and not on page load? I feel like i need to do a "if(isset" somewhere but i can't figure it out.
<head>
<html>
<center>
<body onLoad="document.chip_insert.chip_number.focus()";>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function validateName(){
var x=document.forms["chip_insert"]["order_number"].value;
if (x.length<=10) {
document.forms["chip_insert"]["order_number"].focus();
document.getElementById("order_number").style.border='3px solid red';
document.getElementById("erron").innerHTML = "Invalid";
return false
}
if (x.length=11) {
document.getElementById("order_number").style.border='1px solid black';
document.getElementById("erron").innerHTML = "";
}
if (x==null || x=="")
{
document.forms["chip_insert"]["order_number"].focus();
document.getElementById("order_number").style.border='3px solid red';
document.getElementById("erron").innerHTML = "Invalid";
return false;
}
}
function validateForm(){
var y=document.forms["chip_insert"]["chip_number"].value;
if (y.length<=14) {
document.forms["chip_insert"]["chip_number"].focus();
document.getElementById("chip_number").style.border='3px solid red';
document.getElementById("errcn").innerHTML = "Invalid";
return false
}
if (y==null || y=="")
{
document.forms["chip_insert"]["chip_number"].focus();
document.getElementById("chip_number").style.border='3px solid red';
document.getElementById("errcn").innerHTML = "Invalid";
return false;
}
}
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function isaNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
window.addEventListener('keydown', keydownCallback);
function tabOnEnter(field, event) {
if (event.keyCode === 13) {
if (event.preventDefault) {
event.preventDefault();
} else if (event.stopPropagation) {
event.stopPropagation();
} else {
event.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function keydownCallback(event) {
if (event.keyCode === 191) {
setTimeout(setFocusToTextBox);
}
}
function setFocusToTextBox() {
document.getElementById("order_number").focus();
document.forms["chip_insert"]["order_number"].value="";
document.forms["chip_insert"]["chip_number"].value="";
if (event.preventDefault) {
event.preventDefault();
} else if (event.stopPropagation) {
event.stopPropagation();
} else {
event.returnValue = false;
}
}
</script>
</center>
<center>
<div
style="width:1000px;
height:300px;
border:6px ridge
blue;">
<?php
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
?>
</script>
<style>
h1 {
font-size: 22pt;
font-family: verdana;
}
</style>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<style>
body {
background-image: url("http://JVSIntranet/microchip/image.jpg");
}
</style>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post" onkeydown="keydownCallback(event)">
<label style="font-size:18pt; color:blue; font-family:verdana;" for="order_number">Order Number</label><br>
<input tabindex="1" style="height:40px;font-size:16pt; font-family:verdana;" maxlength="11" type="text" name="order_number" onblur="validateName(order_number)" id="order_number" value="<?php echo $value; ?>" onkeypress="return isNumber(event)" required="required" onkeydown="return tabOnEnter(this, event)" onfocus="this.focus();this.select()" /><span id="erron"></span> <br /><br />
<label style="font-size:18pt; color:blue; font-family:verdana;" for="chip_number">Chip Number</label><br>
<input tabindex="2" style="height:40px;font-size:16pt; font-family:verdana;" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" onkeydown="validateName()" onfocus="this.focus();this.select()" onkeypress="return isaNumber(event)" /><span id="errcn"></span> <br /><br />
<input tabindex="7" type="submit" value="Enter" />
</form>
</center>
<center>
<style>
font { color: red; font-size: 25pt; font-family: verdana; }
</style>
<font>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname"
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
if (!mysqli_query($conn, $sql)) {
echo "ERROR: NUMBER IS ALREADY IN DATABASE! SCAN YOUR CHIP NUMBER AGAIN!";
}
mysqli_close($conn);
?>
</center>
</font>
<center>
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqli = "SELECT * FROM MICROCHIP_TBL ORDER BY entry_date desc LIMIT 20";
$result = $conn->query($sqli);
if ($result->num_rows > 5) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " " . $row["entry_date"] . "::You scanned Order Number--" . $row["order_number"] . "--with Chip Number--" . $row["chip_number"]. "<br>";
}
}else{
echo "0 results";
}
$conn->close();
?>
</center>
</div>
</body>
</head>
</html>
You can do:
if (isset($_POST['submit'])) {
// code to execute on submit
} else {
// code to execute on first request
}
// code to always execute
That's assuming that 'submit' is the name of your submit button, and the form method is post.
One method I see there is to put a hidden field into the form for example:
<input type="hidden" name="IsSubmitted" id="IsSubmitted" value="1" />
Then in your code you check:
if (isset($_POST["IsSubmitted"]) && $_POST["IsSubmitted"] != "")
{
// Do you stuff
}
Simple question from a noob programer. Thinking of several different styles and features to a project i have for a social website. question is this...
can you combine mysqli and PDO style programs?
having difficulty inserting data into database with php, ajax and javascript modules. it says "success" but doesnt insert the info with mysqli. i HAVE used PDO successfully. but my code looks right... it has the same syntax as the tutorial i am looking at with mysqli. this is the code...
<!-- ********************************** -->
<!-- *********** signup.php *********** -->
<!-- ********************************** -->
<?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("php_includes/db_conx.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("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']);
$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
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// 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);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename 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();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="css/style.css">
<style type="text/css">
</style>
<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 != "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>
<?php include_once("includes/template_header.php"); ?>
<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>
</div>
<?php include_once("includes/template_bottom.php"); ?>
</body>
</html>
<!-- ********************************** -->
<!-- *********** activation.php ******* -->
<!-- ********************************** -->
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("php_includes/db_conx.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 ){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}}
?>
<!-- ********************************** -->
<!-- *********** message.php ********** -->
<!-- ********************************** -->
<?php
$message = "";
$msg = preg_replace('#[^a-z 0-9.:_()]#i', '', $_GET['msg']);
if($msg == "activation_failure"){
$message = '<h2>Activation Error</h2> Sorry there seems to have been an issue activating your account at this time. We have already notified ourselves of this issue and we will contact you via email when we have identified the issue.';
} else if($msg == "activation_success"){
$message = '<h2>Activation Success</h2> Your account is now activated. Click here to log in';
} else {
$message = $msg;
}
?>
<div><?php echo $message; ?></div>
<!-- ********************************** -->
<!-- ********* randStrGen.php ********* -->
<!-- ********************************** -->
<?php
function randStrGen($len){
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789$$$$$$$1111111";
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
return $result;
}
?>
is it possible to rewrite so different modules interact?