Script not working as expected when transposed to PHP - javascript

I have written java script to validate signup information but it is not working when i joined it to action.php file.but it works fine in html file.
it also dosen't work after refreshing of the page.i am not getting what is wrong with it.please do help to solve this problem.
it is signup page.
<?php include 'conn.php'; ?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="signup.css">
</head>
<body onload="form.reset();"">
<div class="container">
<div id="grad">
<ul>
<li style="">Helping Hands...</li>
<li style="float:right"><a class="active" href="#about"> Have an account? Log in</a></li>
</ul>
</div>
<form name=form action="#" onsubmit="return validate()" autocomplete=on method="post">
<div class="outsidebox" >
<div class='login'>
<h2>Register</h2>
<div class="agree1">
<label style="margin-left: 30px;"> <input id="ngo" type="radio" name="option" value="ngo" checked>NGO</label>
<label style="margin-left:30px;"><input id="ind" type="radio" name="option" value="ind">INDIVIDUAL</label>
</div>
<span><input name='uname' placeholder='Username' type='text' value='<?php echo $_SESSION['name']; $_SESSION['name']='';?>'>
<p id="username" style="font-size: 12px;color:red;"></p>
</span>
<span><input name='email' placeholder='E-Mail Address' type='text'>
<p id="email" style="font-size: 12px;color:red;"></p></span>
<span> <input name='password' placeholder='Password' type='password'>
<p id="password" style="font-size: 12px;color:red;"></p></span>
<span><input name='passwordcon' placeholder=' Confirm Password' type='password'>
<p id="passwordcon" style="font-size: 12px;color:red;"></p></span>
<span><input name='fullname' placeholder='Enter Your Full Name ' type='text'>
<p id="fullname" style="font-size: 12px;color:red;"></p></span>
<div id="a1" >
<strong>PLEASE SELECT FIELDS</strong><br>
<div class="fields">
<select name="fields" id="fields">
<option value="child">Child Welfare</option>
<option value="education">Child Education</option>
<option value="relief">Disaster Management and relief</option>
<option value="envir">Environment</option>
<option value="animals">Animals</option>
</select>
</div>
</div>
<div class='agree'>
<input id='agree' name='agree' type='checkbox'>
<label for='agree'></label>Accept rules and conditions
</div>
<input class='animated' type='submit' value='Register'>
<a class='forgot' href='#'>Already have an account?</a>
</div>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ngo").click(function(){
$("#a1").show();
});
$("#ind").click(function(){
$("#a1").hide();
});
});
</script>
<script language="javascript">
function validate(){
var flag=1;
var form=document.forms.form;
var user=form.username.value;
if(user==null || user==""){
user="please enter username";
document.getElementById("username").innerHTML=user;
flag=0;
}
else{
document.getElementById("username").innerHTML="";
}
var email=form.email.value;
if(email==null ||email==""){
email="please enter email";
document.getElementById("email").innerHTML=email;
flag=0;
}
else{
document.getElementById("email").innerHTML="";
}
var password=form.password.value;
if(password==null || password==""){
password="please enter password";
document.getElementById("password").innerHTML=password;
flag=0;
}
else{
document.getElementById("password").innerHTML="";
}
var passwordcon=form.passwordcon.value;
if(passwordcon==null || passwordcon==""){
passwordcon="please conform password";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
if(passwordcon!=password){
passwordcon =" pasword confirmation fail";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
var fullname=form.fullname.value;
if (fullname==null || fullname=="") {
fullname="Enter full name";
document.getElementById("fullname").innerHTML=fullname;
flag=0;
}
else{
document.getElementById("fullname").innerHTML="";
}
if(flag==0){
return false;
}
else{
return true;
`enter code here` }
}
</script>
</html>
it is my action.php as inputs.php in which i have written defined session variables.to send error to signup page;and also i am performing
email validation check.Then i check username is used or not to insert this
into the database.
.
<?php include 'conn.php'; ?>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$password=$_POST["password"];
$fullname=$_POST["fullname"];
$uname=$_POST["uname"];
$ngo=$_POST["option"];
$field=$_POST["field"];
$email=$_POST["email"];
$_SESSION['uerr']='';
$_SESSION['emailerr']='';
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === true){
$emailerr="Inavalid Email";
$_SESSION['email']=$emailerr;
$sql="SELECT * FROM user WHERE uname='$uname' LIMIT 1";
$result=mysqli_query($conn,$sql);
$countu= mysqli_num_rows($result);
echo "in emailerr".$countu;
if($countu==0)
{
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['name']=$uname;
$_SESSION['emailerr']=$emailerr;
$_SESSION['email']='';
die(header('Location:signup2.php'));
}
else{
$uerr="USER NAME already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['name']='';
$_SESSION['uerr']=$uerr;
$_SESSION['emailerr']=$emailerr;
$_SESSION['email']='';
echo "in esle";
die(header('Location:signup2 .php'));
}
}
/* $sql="SELECT * FROM user WHERE uname='$uname' LIMIT 1";
$result=mysqli_query($conn,$sql);
$countu= mysqli_num_rows($result);
$sql="SELECT * FROM user WHERE email='$email' LIMIT 1";
$result=mysqli_query($conn,$sql);
$counte = mysqli_num_rows($result);
if($counte==1 && $countu==1)
{
$uerr="USER NAME already taken";
$emailerr="email already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['emailerr']=$emailerr;
$_SESSION['uerr']=$uerr;
echo "in bothlerr";
die(header('Location:signup1.php'));
}
elseif($counte==1)
{
$emailerr="email already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['name']=$uname;
$_SESSION['emailerr']=$emailerr;
$_SESSION['email']='';
echo "in boeerr";
die(header('Location:signup1.php'));
}
elseif($countu==1)
{
$uerr="USER NAME already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['email']=$email;
$_SESSION['uerr']=$uerr;
$_SESSION['name']='';
echo "in uerr";
die(header('Location:signup1.php'));
}
else{
if($ngo="ngo"){
date_default_timezone_set("Asia/Kolkata");
$date=date("Y-m-d h:i:s");
$sql="INSERT INTO user(uname,email,password,dtime,full_name,field) VALUES ( '$uname', '$email', '$password','$date','$fullname','$field')";
mysqli_query($conn,$sql);
echo "in ngo data inserted";
}
else{
date_default_timezone_set("Asia/Kolkata");
$date=date("Y-m-d h:i:s");
$field='none';
$sql="INSERT INTO user(uname,email,password,dtime,full_name,field) VALUES ( '$uname', '$email', '$password','$date','$fullname','$field')";
mysqli_query($conn,$sql);
echo "in ind datainserted";
}
}*/
}
?>
and last one is main signup.html file in which javascript works well.
i want to perform some error checking that is why i have saved it as
signup2.php in htdocs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="signup.css">
</head>
<body onload="form.reset();"">
<div class="container">
<div id="grad">
<ul>
<li style="">Helping Hands...</li>
<li style="float:right"><a class="active" href="#about"> Have an account? Log in</a></li>
</ul>
</div>
<form name=form action="#" onsubmit="return validate()" autocomplete=on method="post">
<div class="outsidebox" >
<div class='login'>
<h2>Register</h2>
<div class="agree1">
<label style="margin-left: 30px;"> <input id="ngo" type="radio" name="option" value="ngo" checked>NGO</label>
<label style="margin-left:30px;"><input id="ind" type="radio" name="option" value="ind">INDIVIDUAL</label>
</div>
<span><input name='username' placeholder='Username' type='text'>
<p id="username" style="font-size: 12px;color:red;"></p>
</span>
<span><input name='email' placeholder='E-Mail Address' type='text'>
<p id="email" style="font-size: 12px;color:red;"></p></span>
<span> <input name='password' placeholder='Password' type='password'>
<p id="password" style="font-size: 12px;color:red;"></p></span>
<span><input name='passwordcon' placeholder=' Confirm Password' type='password'>
<p id="passwordcon" style="font-size: 12px;color:red;"></p></span>
<span><input name='fullname' placeholder='Enter Your Full Name ' type='text'>
<p id="fullname" style="font-size: 12px;color:red;"></p></span>
<div id="a1" >
<strong>PLEASE SELECT FIELDS</strong><br>
<div class="fields">
<select name="fields" id="fields">
<option value="child">Child Welfare</option>
<option value="education">Child Education</option>
<option value="relief">Disaster Management and relief</option>
<option value="envir">Environment</option>
<option value="animals">Animals</option>
</select>
</div>
</div>
<div class='agree'>
<input id='agree' name='agree' type='checkbox'>
<label for='agree'></label>Accept rules and conditions
</div>
<input class='animated' type='submit' value='Register'>
<a class='forgot' href='#'>Already have an account?</a>
</div>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ngo").click(function(){
$("#a1").show();
});
$("#ind").click(function(){
$("#a1").hide();
});
});
</script>
<script language="javascript">
function validate(){
var flag=1;
var form=document.forms.form;
var user=form.username.value;
if(user==null || user==""){
user="please enter username";
document.getElementById("username").innerHTML=user;
flag=0;
}
else{
document.getElementById("username").innerHTML="";
}
var email=form.email.value;
if(email==null ||email==""){
email="please enter email";
document.getElementById("email").innerHTML=email;
flag=0;
}
else{
document.getElementById("email").innerHTML="";
}
var password=form.password.value;
if(password==null || password==""){
password="please enter password";
document.getElementById("password").innerHTML=password;
flag=0;
}
else{
document.getElementById("password").innerHTML="";
}
var passwordcon=form.passwordcon.value;
if(passwordcon==null || passwordcon==""){
passwordcon="please conform password";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
if(passwordcon!=password){
passwordcon =" pasword confirmation fail";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
var fullname=form.fullname.value;
if (fullname==null || fullname=="") {
fullname="Enter full name";
document.getElementById("fullname").innerHTML=fullname;
flag=0;
}
else{
document.getElementById("fullname").innerHTML="";
}
if(flag==0){
return false;
}
else{
return true;
}
}
</script>
</html>

You need to clean up your code and format your HTML properly before proceeding with troubleshooting should you still not be able to achieve your intended purpose after this exercise.
As pointed out in comments below your initial post, you code contains lots of problems and need to be well formed;
Your </head> element should have a <title> instance.
You should have <body onload="form.reset();"> (without the extra double quotes at the end, after the semi-column).
Remember to close your <div class="container">; it's currently not.
Your <p> elements should not be child elements of <span> as this is actually not allowed according to your declared document type definition, <!DOCTYPE html>.... more details here, for <p>, and here, for <span>.
Close your <body> tag right before your </html>; not after </form>.
Your JavaScript contents are still part of your page content and as such should be within the opened and closed body tag if not declared in your head section.
Feel free to omit the language="javascript" attribute on your <script> element; it's obsolete.

Related

Use javascript code in php in function.php file

I write this code for a login form in function.php file in Wordpress:
$name = $_POST['dx'];
$pass = $_POST['SX'];
$submitbutton= $_POST['commit'];
if ( isset($submitbutton) ) {
if( isset($name) && empty($name) ){
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "username is empty";
errorMsg.style.display = "block"; </script>';
}
else if( isset($pass) && empty($pass) ){
$name = "";
$pass = "";
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "password is empty";
errorMsg.style.display = "block"; </script>';
}
}
I got an error Cannot read property 'style' of null
HTML code
<div class="login">
<ul class="errorMessages" id="errorMsg">
<li></li>
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30"
class="keyboardInput" vki_attached="true">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
I want to check the form fields, if fields were empty, show the error messege above the form.
Something like this image:
How can I use script code in right way in PHP? and how can I resolve this error?
<div class="login">
<ul class="errorMessages" id="errorMsg">
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30" class="keyboardInput" vki_attached="true"><img src="http://account.taminm.ir/wp-content/uploads/2020/01/keyboard.png" alt="Display virtual keyboard interface" class="keyboardInputInitiator" title="Display virtual keyboard interface">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
<script type="text/javascript">
const loginWrapper = document.querySelector('.login'),
errorContainer = loginWrapper.querySelector('.errorMessages'),
form = loginWrapper.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const username = form.querySelector('#dx').value.trim(),
password = form.querySelector('#SX').value.trim();
if ( !username ) {
errorContainer.innerHTML = 'username is empty';
} else if (!password) {
errorContainer.innerHTML = 'password is empty';
} else {
form.submit()
}
});
</script>

Creating AJAX registration form

I created a registration form following an online tutorial.
The current code doesn't insert anything into a database yet. I am just trying to get the basic error messages working.
When the form is submitted the error message "There was an error" is shown. This comes from my action page where the register button has been pressed.
I am not sure what has caused this.
I know there is a lot of code.
Any help is appreciated.
Main Page(With my form):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var forename = $("#txtfirstname").val();
var surname = $("#txtsurname").val();
var username = $("#txtusername").val();
var password = $("#txtpassword").val();
$(".form-message").load("aregisteraction.php", {
forename : forename,
surname : surname,
username : username,
password : password
});
});
});
</script>
</head>
<body>
<?php
require 'leftnav.php';
?>
<div class="two-thirds column">
<h1> Not Registered?</h1>
<h3>Register</h3>
<form method="post" action="aregisteraction.php">
<p>
<label for="txtfirstname" >Firstname: </label> </br>
<input type="text" name="firstname" id="txtfirstname" />
</p>
<p>
<label for="txtsurname" >Surname: </label> </br>
<input type="text" name="surname" id="txtsurname" />
</p>
<p>
<label for="ddage" >Age: </label> </br>
<select name="ddage">
<option value="0">Select a value</option>
<option value="1">0-10</option>
<option value="2">11-30</option>
<option value="3">31-50</option>
<option value="4">51-70</option>
<option value="4">71+</option>
</select>
</p>
<p>
<label >Gender: </label> </br>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
</p>
<p>
<label for="txtusername" >Email: </label> </br>
<input type="text" name="username" id="txtusername" />
</p>
<p>
<label for="txtpassword" >Password: </label> </br>
<input type="password" name="password" id="txtpassword" />
</p>
<p>
<label for="txtpassword1" >Re-enter Password: </label> </br>
<input type="password" name="password1" id="txtpassword1" />
</p>
<input type="submit" name="register" value="Register" />
<p class="form-message"></p>
</form>
Action Page:
<?php
if(isset($_POST['register'])){
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$username = $_POST['username'];
$password = $_POST['password'];
$errorEmpty = false;
$errorEmail = false;
if(empty($forename)||empty($surname)||empty($username)||empty($password)){
echo "<span> Fill in all fields </span>";
$errorEmpty = true;
}
elseif (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'> Fill in a valid email </span>";
$errorEmail = true;
}
else{
echo "<span class='form-success'> Success </span>";
}
}
else{
echo "There was an error!";
}
?>
<script>
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").removeClass("input-error");
var errorEmpty ="<?php echo $errorEmpty; ?>";
var errorEmail ="<?php echo $errorEmail; ?>";
if(errorEmpty == true){
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").addClass("input-error");
}
if(errorEmail == true){
$("#txtusername").addClass("input-error");
}
if(errorEmail == false && errorEmpty == false){
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").val("");
}
</script>
In your JavaScript you doesn't send any value for register.
Two options: add a value to register:
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var forename = $("#txtfirstname").val();
var surname = $("#txtsurname").val();
var username = $("#txtusername").val();
var password = $("#txtpassword").val();
$(".form-message").load("aregisteraction.php", {
forename : forename,
surname : surname,
username : username,
password : password,
register: "ok",
});
});
});
Or simply test $_POST on another field (as register is a button and will always contains a value in the form).
Also, to test values of your form in PHP you can user print_r():
print_r($_POST);

Same structure, but Ajax success response acts differently from previous version

Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"&region="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().

can't post the data from form on a pop-up?

i would like to made a pop-up window for my login and signup sites. but there's a problem with this code, can't post the data from the form and the submit button didn't work when clicked. someone help me please. thanks.
here it is the index.html with the pop-up:
<div class="popup">
<h2>Welcome Guest!</h2>
<form id="formlogin" name="formlogin" method="POST" action="login_proses.php" enctype="multipart/form-data" autocomplete="on">
<p>Please enter your login and password here</p>
<p>
<label for="username">Login</label>
<input type="text" id="username" name="username" value="" required />
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password" value="" required/>
</p>
<p>
<input type="submit" value="Log In" onclick="popupUploadForm()">
</p>
</form>
<a class="close" href="#close"></a>
</div>
<script>
function popupUploadForm(){
var newWindow = window.location.href='login_proses.php';
}
</script>
and here it is login_proses.php that pick the data form, but it's always failed, and always go into index.html as else condition.
<?php
session_start();
include "connect.php";
if (isset($_POST["username"])){
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql=mysql_query("select * from member where username='$username'");
if ($sql && mysql_num_rows($sql)>0){
$result=mysql_fetch_array($sql);
if($password == $result['password']){
$_SESSION['username']=$username;
echo "<script type='text/javascript'>alert('Selamat Datang $username');
window.location.href='member.php';</script>";
}
else{
echo "<script type='text/javascript'>alert('Password salah, silahkan coba lagi');history.go(-1)</script>" ;
}
}
else{
echo "<script type='text/javascript'>alert('Username tidak ada dalam database');history.go(-1)</script>" ;
}
} else {
header("location:index.html");
} ?>

Form field validation seems to be ignored

I feel like I must be missing something so simple as this form field validation method has worded well in the past for me. I believe all file paths are correct, but any time I hit submit it generates an email regardless of the field content.
The test site is PortfolioPrep
<form action="<?php echo base_url()?>" method="POST">
<input type="hidden" name="subject" id="subject" value="Portfolio Prep From Reply">
<div class="dot_spacer_lt_green"></div>
<label>NAME</label><dl class="field row">
<dt class="text"><input name="name" type="text" id="name" placeholder="Contact Name" /></dt>
<dd class="msg"><span class="caret"></span>You filled this out wrong.</dd>
</dl>
<label>EMAIL</label><dl class="field row">
<dt class="text"><input name="from" type="text" id="from" placeholder="Contact Email" /></dt>
<dd class="msg"><span class="caret"></span>You filled this out wrong.</dd>
</dl>
<div class="dot_spacer_lt_green"></div>
<ul class="field row">
<li>
<label class="radio" for="high_school">HIGH SCHOOL</label>
<input name="radio1" type="radio" form="high_school" value="High School">
</li>
<li>
<label class="radio" for="recent_graduate">RECENT GRADUATE</label>
<input name="radio1" type="radio" form="recent_graduate" value="Recent Graduate">
</li>
</ul>
<div class="dot_spacer_lt_green"></div>
<dl class="field row">
<dt class="textarea"><textarea name="message" id="message" placeholder="Text Field"></textarea></dt>
<dd class="error msg"><span class="caret"></span>You filled this out wrong.</dd>
</dl>
<input type="image" src="<?php echo base_url()?>img/submit.png" alt="Submit" onClick="return validateForm()"/>
<div class="dot_spacer_lt_green"></div>
</form>
</div>
<div class="one columns"></div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="<?php echo base_url()?>js/libs/jquery-1.7.2.min.js"><\/script>')</script>
<script src="<?php echo base_url()?>js/libs/gumby.min.js"></script>
<script src="<?php echo base_url()?>js/plugins.js"></script>
<script src="<?php echo base_url()?>js/main.js"></script>
<script src="<?php echo base_url()?>js/libs/modernizr-2.0.6.min.js"></script>
<!-- end scripts-->
<!-- Change UA-XXXXX-X to be your site's ID -->
<script>
$(document).ready(function(e) {
$("#from").blur(function(){
if($(this).val()=='' )
{
$(this).css('color','#000');
$(this).val('Email')
}
});
$("#fron").click(function(){
if($(this).val()=='Email' || $("#fron").val()=='Please enter a valid email.' || $("#from").val()=='Please enter your email.')
{$(this).val('')}
});
$("#name").blur(function(){
if($(this).val()=='')
{$(this).css('color','#000');
$(this).val('Contact Name')}
});
$("#name").click(function(){
if($(this).val()=='Please enter your name.' || $(this).val()=='Contact Name')
{$(this).val('')}
});
function validateForm()
{
var i=0;
if($("#name").val()=='Contact Name' || $("#name").val()=='Please enter your name.')
{ $("#name").css('color','red');
$("#name").val('Please enter your name.');
i++;
}
if($("#from").val()=='Email' || $("#from").val()=='Please enter your email.' || $("#from").val()=='Please enter a valid email.')
{
$("#from").css('color','red');
$("#from").val('Please enter your email.');
i++;
}
else
{
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(!filter.test($("#from").val()))
{
$("#from").css('color','red');
$("#from").val('Please enter a valid email.');
i++;
}
}
if(i>0)
{
return false;
}
else{
//$("#contactusform").submit();
}
}
window._gaq = [['_setAccount','UAXXXXXXXX1'],['_trackPageview'],['_trackPageLoadTime']];
Modernizr.load({
load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'
});
</script>
You have some typos in your Javascript:
"#fron" needs to become "#from" in the following section:
$("#fron").click(function(){
if($(this).val()=='Email' || $("#fron").val()=='Please enter a valid email.' || $("#from").val()=='Please enter your email.')
{$(this).val('')}
});

Categories

Resources