Checking if a PHP array is empty in JavaScript - php

Hi I have a form where a user can enter one or more books into a DB. Whenever a user enters one book and forgets to enter the title, a JavaScript alert comes and alerts him to enter a title. Now if he has two or more books and he forgets to enter the title, the alert doesn't show up.
This is my JavaScript function.
function validateForm()
{
var a=document.forms["submit_books"]["title"].value;
if (a==null || a=="")
{
alert("Please enter a Title");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.submit_books.email.value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
}
And Here is my PHP code
<form method="post" name="submit_books" onsubmit="return validateForm()" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php for ($i=1; $i<$num_of_books + 1; $i++){
echo "<strong>Book # $i</strong><br><br>";
?>
<label for="title">*Title</label>: <input type="text" id="title" size="60" name="title[]" autocomplete="off"/><br><br>
<?php }?>
<input type="submit" name="submit" value="Submit Books">
</form>
I even tried putting the PHP array into a JavaScript one.
<?
$js_array = json_encode($title);
echo "var title = ". $js_array . ";\n";
?>
var index = 1;
if( index < title.length)
{
alert("Please enter a Title");
return false;
}
There must be an easier way doing this

You should be doing
var index = 1;
if( index > title.length )
{
alert("Please enter a Title");
return false;
}
Since there is no record if title.length = 0, that is, if 1 > 0 then there is no title.
You can also check
if( title.length === 0 )

Try to use inside html form
<label>
<span>Book Title: (required)</span>
<input name="book" type="text" placeholder="Please enter your books title" required autofocus>
</label>
Then use javascript to validate
(function() {
// Create input element for testing
var inputs = document.createElement('input');
// Create the supports object
var supports = {};
supports.autofocus = 'autofocus' in inputs;
supports.required = 'required' in inputs;
supports.placeholder = 'placeholder' in inputs;
// Fallback for autofocus attribute
if(!supports.autofocus) {
}
// Fallback for required attribute
if(!supports.required) {
}
// Fallback for placeholder attribute
if(!supports.placeholder) {
}
// Change text inside send button on submit
var send = document.getElementById('submit');
if(send) {
send.onclick = function () {
this.innerHTML = '...Processing';
}
}
})();

You can do this like:
<?
echo "var title_length = ". count($title) . ";\n";
?>
var index = 1;
if( index > title_length)
{
alert("Please enter a Title");
return false;
}

Related

keeping first field in html form after submitting then have a master submit button after someone is done with the first field

I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?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 "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
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 tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"

How to validate form in jQuery and PHP

I have a registration form that I want to validate using jQuery and than pass it to PHP to login if all details are correct.
I am trying to use Yendesigns form - http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/
My form code is:
<?php
require_once("includes/initialise.php");
if (isset($_POST['resetpassword']) && $_POST['resetpassword'] == 'resetnow') {
$required = array('first_name','last_name','username','email','password','password2');
$missing = array();
$validation = array(
'first_name' => 'Please provide your first name',
'last_name' => 'Please provide your last name',
'username' => 'Please provide your username',
'email' => 'Please provide your valid email address',
'password' => 'Please provide your password',
'password2' => 'Please confirm your password',
'userdup' => 'Username already registered',
'emaildup' => 'Email address already registered',
'mismatch' => 'Passwords do not match'
);
//Sanitise and clean function
$first_name = escape($_POST['first_name']);
$last_name = escape($_POST['last_name']);
$username = escape($_POST['username']);
$email = escape($_POST['email']);
$password = escape($_POST['password']);
$password2 = escape($_POST['password2']);
foreach($_POST as $key => $value) {
$value = trim($value);
if(empty($value) && in_array($key,$required)) {
array_push($missing,$key);
} else {
${$key} = escape($value);
}
}
if($_POST['email'] !="" && getDuplicate(1,'email','clients','email',$email)) {
array_push($missing,'emaildup');
}
if($_POST['username'] !="" && getDuplicate(1,'username','clients','username',$username)) {
array_push($missing,'userdup');
}
// Check User Passwords
if( strcmp($_POST['password'], $_POST['password2']) != 0 ) {
array_push($missing,'mismatch');
}
//validate email address
if(!empty($_POST['email']) && !isEmail($_POST['email'])) {
array_push($missing,'email');
}
if(!empty($missing)) {
$before = " <span class=\"errorred\">";
$after = "</span>";
foreach($missing as $item)
${"valid_".$item} = $before.$validation[$item].$after;
} else {
// stores MD5 of password
$passmd5 = md5($_POST['password']);
// stores clients IP addresss
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$date = date('Y-m-d');
$time = date('H:i:s');
// Generates activation code simple 4 digit number
$hash = mt_rand().date('YmdHis').mt_rand();
//Insert Data
$sql = "INSERT INTO clients(first_name, last_name, username, email, password, date, time, `hash`)
VALUES ('{$first_name}','{$last_name}','{$username}','{$email}','$passmd5','$date', '$time','$hash')";
$result = mysql_query($sql, $conndb) or die(mysql_error());
if($result) {
$to = $_POST['email'];
$subject = 'Activate your account';
$from = 'dummy#emailaddress.co.uk';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
$headers .= "From: My Website Name <".$from.">\r\n";
$headers .= "Reply-to: My Website Name <".$from.">\r\n";
$message = '<div style="font-family:Arial, Verdana, Sans-serif; color:#333; font-size:12px">
<p>Thank you for registering on our website</p>
<p>Please click on the following link to activate your account:
http://'.$host.''.$path.'/activate.php?id='.$hash.'</p>
<p>Here are your login details...</p>
<p>User Name: '.$username.'</p>
<p>Email: '.$email.' </p>
<p>Passwd: '.$password.' </p>
</p></div>';
if (mail($to, $subject, $message, $headers)) {
$confirmation = '<p>Thank you.<br />You have successfully registered.</p>';
} else {
$confirmation = '<p>Error.<br />Your activation link could not be sent.<br />Please contact administrator.</p>';
}
}
}
}
require_once("includes/header.php");
?>
<div class="block">
<div class="block_head">
<div class="bheadl"></div>
<div class="bheadr"></div>
<h5>Register</h5>
<ul>
<li>Login</li>
</ul>
</div> <!-- .block_head ends -->
<div class="block_content">
<?php echo isset($confirmation) ? $confirmation : NULL; ?>
<form name="register" id="customForm" action="" method="post">
<div>
<label for="first_name">First Name: * <?php echo isset($valid_first_name) ? $valid_first_name : NULL; ?></label>
<input id="first_name" name="first_name" type="text" class="fld" value="" />
<span id="first_nameInfo"></span>
</div>
<div>
<label for="last_name">Last Name: * <?php echo isset($valid_last_name) ? $valid_last_name : NULL; ?></label>
<input id="last_name" name="last_name" type="text" class="fld" value="" />
<span id="last_nameInfo"></span>
</div>
<div>
<label for="username">Username: * <?php echo isset($valid_username) ? $valid_username : NULL; ?> <?php if(isset($valid_userdup)) { echo $valid_userdup; } ?></label>
<input id="username" name="username" type="text" class="fld" value="" />
<span id="usernameInfo"></span><span id="status"></span>
</div>
<div>
<label for="email">E-mail: * <?php if(isset($valid_email)) { echo $valid_email; } ?> <?php if(isset($valid_emaildup)) { echo $valid_emaildup; } ?></label>
<input id="email" name="email" type="text" class="fld" value="" />
<span id="emailInfo"></span>
</div>
<div>
<label for="pass1">Password: * <?php if(isset($valid_password)) { echo $valid_password; } ?></label>
<input id="pass1" name="pass1" type="password" class="fld" value="" />
<span id="pass1Info"></span>
</div>
<div>
<label for="pass2">Confirm Password: * <?php if(isset($valid_password2)) { echo $valid_password2; } ?> <?php if(isset($valid_mismatch)) { echo $valid_mismatch; } ?></label>
<input id="pass2" name="pass2" type="password" class="fld" value="" />
<span id="pass2Info"></span>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</table>
<input type="hidden" name="resetpassword" value="resetnow" />
</form>
</div>
<!-- .block_content ends -->
<div class="bendl"></div>
<div class="bendr"></div>
</div>
<?php
require_once("includes/footer.php");
?>
And the jquery is:
/***************************/
//#Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro
//#website: www.yensdesign.com
//#email: yensamg#gmail.com
//#license: Feel free to use it, but keep this credits please!
/***************************/
$(document).ready(function(){
//global vars
var form = $("#customForm");
var first_name = $("#first_name");
var first_nameInfo = $("#first_nameInfo");
var last_name = $("#last_name");
var last_nameInfo = $("#last_nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
//On blur
first_name.blur(validateName);
last_name.blur(validateLastName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
first_name.keyup(validateName);
last_name.keyup(validateLastName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateLastName() & validateEmail() & validatePass1() & validatePass2() & validateMessage())
return true
else
return false;
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
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 it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Please provide a valid email address");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(first_name.val().length < 4){
first_name.addClass("error");
first_nameInfo.text("Please provide your first name (more than 3 letters)");
first_nameInfo.addClass("error");
return false;
}
//if it's valid
else{
first_name.removeClass("error");
first_nameInfo.text("");
first_nameInfo.removeClass("error");
return true;
}
}
function validateLastName(){
//if it's NOT valid
if(last_name.val().length < 4){
last_name.addClass("error");
last_nameInfo.text("Please provide your first name (more than 3 letters)");
last_nameInfo.addClass("error");
return false;
}
//if it's valid
else{
last_name.removeClass("error");
last_nameInfo.text("");
last_nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Please provide your password (at least 5 characters)");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
});
When I click the submit button the form passes via php and stops the jquery. If the submit button is not pressed than it carries on validating via jQuery.
How can I get it to if all details are correct to pass the PHP validation too. If errors or user has jQuery disabled to validate via PHP?
Thank you
A good web application has two layers of validation:
The input is validated client side with javascript (e.g. jquery). It gives better feedback for the user if the validation is done immediately without contacting the server.
The input is validated server side to guard against malicious users having bypassed the client side validation (or simply a user with javascript disabled). There are also cases where validation rules are hard to implement client side.
If you want to test your server side validation, the easiest is probably to temporary disable javascript in the browser.
METHOD 1: In your jQuery (untested):
$("#send").click(function(e) {
e.preventDefault();
// call javascript validation functions here
// if valid then submit form:
$("#customForm").submit();
});
EDIT: If user has not got javascript, then the form will be submitted as usual and validated by php only when the submit button is clicked. But if javascript is enabled, then the default submit action will be prevented, and you can first check whatever you want to check on the client side before submitting the form.
METHOD 2: Instead of the jQuery code above, you can instead call your javascript validation functions with an onSubmit="return validate();" form attribute, where validate() javascript function returns false if there are errors. This will also prevent the form from submitting directly - unless the user does not have javascript.
UPDATE IN RESPONSE TO ZAFER's COMMENT:
In method 1, might be better to use this instead:
$("#customForm").submit(function(e) {
e.preventDefault();
// call javascript validation functions here
// if valid then submit form:
$(this).submit();
});
to insert into a database i use this function.
/**
* Takes an array or string and takes out malicous code.
* #param array|string $var
* #param string $key
* #return string
*/
function aspam($var, $returnZero = false, $key = '') {
if (is_array($var) && !empty($key)) {
/*
* if var is array and key is set, use aspam on the array[key]
* if not set, return 0 or ''
*/
if (isset($var[$key])) {
return general::aspam($var[$key], $returnZero);
} else {
return ($returnZero) ? 0 : '';
}
} elseif (is_array($var) && empty($key)) {
/*
* if var is array and key is empty iterate through all the members
* of the array and aspam the arrays and take out malicous code of the
* strings or integers.
*/
$newVar = array();
$newVal = '';
foreach ($var as $key => $val) {
if (is_array($val)) {
$newVal = general::aspam($val, $returnZero);
} elseif (!empty($val)) {
$newVal = trim(htmlspecialchars($val, ENT_QUOTES));
} else {
$newVal = ($returnZero) ? 0 : '';
}
$newVar[$key] = $newVal;
}
return $newVar;
} elseif (!empty($var)) {
/*
* Strip malicous code
*/
return trim(htmlspecialchars($var, ENT_QUOTES));
} else {
/*
* return default 0 | '' if string was empty
*/
return ($returnZero) ? 0 : '';
}
}
to use this function you put in the array, then tell it if you want to return empty or 0.
$product_id = aspam($_REQUEST, true, 'product_id');
The javascript with jquery you can itterate through a class and validate all at once.
/*variable to check if it is valid*/
var returnVar = true;
$('.required').each(function () {
if ($(this).is("select")) {
if ($(this).val() > '0') {
/*Code for is valid*/
$(this).parent().removeClass("alert-danger");
} else {
/*Code for is not valid*/
$(this).parent().addClass("alert-danger");
returnVar = false;
}
} else {
if (!$(this).val()) {
/*Code for is valid*/
$(this).parent().addClass("alert-danger");
returnVar = false;
} else {
/*Code for is not valid*/
$(this).parent().removeClass("alert-danger");
}
}
});
if(returnVar){
/*submit form*/
}

having issues to validate form using JavaScript

On this form when I enter the email address correctly and leaves the name field as a blank, the page is submitting and the javacript not running. Otherwise its working fine.
Please someone help me to solve this JavaScript.
function validateform(data)
{
var validField = "";
var namevalid=/^[a-zA-Z ]+$/;
if(data.name.value == ""){validField += "- Please Enter Your Name\n";}
else if(data.name.value.search(namevalid)==-1){validField += "- Entered Name contains Numbers or Symbols\n";}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;
}
<form name="data" onsubmit="return validateform(this);" action="some.php" method="post">
<div>
<label>Name:</label><input type="text" id="name" name="name" size="20" maxlength="20"/></div>
<div>
<label>E- mail Address:</label><input type="text" id="email" name="email" size="20" maxlength="30"/></div>
<input type="submit" name="submit" value="Start Now!"/>
</form>
You need little change in your code. Problem is because function validateform() always returning false irrespective of email validation. Test below working page along with your code. You should add alert and return false in else {} block.
<html>
<head>
<script type="text/javascript">
function validateform(data)
{
var validField = "";
var namevalid=/^[a-zA-Z ]+$/;
if(data.name.value == ""){validField += "- Please Enter Your Name\n";}
else if(data.name.value.search(namevalid)==-1){validField += "- Entered Name contains Numbers or Symbols\n";}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
else {
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;
}
}
</script>
</head>
<body>
<form name="data" onsubmit="return validateform(this);" action="some.php" method="post">
<div>
<label>Name:</label><input type="text" id="name" name="name" size="20" maxlength="20"/></div>
<div>
<label>E- mail Address:</label><input type="text" id="email" name="email" size="20" maxlength="30"/></div>
<input type="submit" name="submit" value="Start Now!"/>
</form>
</body>
</html>
You need to refactor your code a little bit. At the minute if the email address is valid your return true out of the function regardless of the name field.
function validateform(data) {
var validField = "";
var isValid = false;
var namevalid = /^[a-zA-Z ]+$/;
if (data.name.value == "") {
validField += "- Please Enter Your Name\n";
}
else if (data.name.value.search(namevalid) == -1) {
validField += "- Entered Name contains Numbers or Symbols\n";
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value))) {
validField += "- Please Enter A Valid E-mail Address\n";
};
if (validField == "") {
isValid = true;
}
if (!isValid) {
alert(validField);
}
return isValid;
}
You need to place your function between <script> tags, other than that this looks ok to me.
I'm not quite sure why this is failing, but the function isn't called at all. Might be the onsubmit.
Why don't you use a library like jQuery?
Have a look at this example, this works fine: http://jsfiddle.net/tR3XQ/1/
$("form[name=data]").submit(function(){
var validField = "";
var namevalid=/^[a-zA-Z ]+$/;
if(data.name.value == ""){validField += "- Please Enter Your Name\n";}
else if(data.name.value.search(namevalid)==-1){validField += "- Entered Name contains Numbers or Symbols\n";}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;
});​
You need to add a check for a value in validField for the email check otherwise it is ignored
if (validField.length = 0 && /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;

Javascript: Show element in a form when something is valid

How can I display an element when something in a form is validated?
Here's some of my code:
signup.php
<div class="wrapper">
<div class="error-div" id="zipcode-error" ></div>
<label>Zip code:</label>
<input type="text" class="input" name="zipcode" id="zipcode" />
</div>
<!-- this div is hidden, it can only be seen when zip code is validated -->
<div class="wrapper" id="city-wrapper" >
<div class="error-div" id="city-error" ></div>
<label>City:</label>
<input type="text" class="input" name="city" id="city" >
</div>
<!-- this div is hidden, it can only be seen when zip code is validated -->
signup_validation.js
$('#zipcode').keyup(function() {
$.post('action/validate_signup.php?key=zipcode', { zipcode: $(this).val() },
function(result){
$('#zipcode-error').html(result).show("slow");
});
});
validate_signup.php
if(isset($_POST['zipcode'])){
$zip = $_POST['zipcode'];
if(empty($zip)){
echo "*Zipcode required!";
}elseif( (strlen($zip)<5) OR (strlen($zip)>5)){
echo "*Must be 5 digit!";
}elseif(!is_numeric($zip)){
echo "Must be numeric!";
}else{
$query = mysql_query("SELECT * FROM zip_codes WHERE zip = '{$zip}'");
$found_zip = mysql_num_rows($query);
if($found_zip =1){
echo "<img src='images/check.jpg' /><input type = 'hidden' name='show-city' id='show-city' />";
} else{
echo "Zip not found";
}
}
}
When zipcode is validated i want to display the City div, but i don't know how.
The situation goes like this: a user must input his/her valid zipcode, once it's validated, the hidden div will come up and display it's corresponding City on the text field provided.
if($found_zip =1){
echo "found||<img src='images/check.jpg' /><input type = 'hidden' name='show-city' id='show-city' />";
} else{
echo "error||error";
}
//then ur js
$('#zipcode').blur(function() {
var zip = $(this).val();
$.post('action/validate_signup.php?key=zipcode', { zipcode: zip },
function(result){
var respArr = result.split("||");
if("error" ==respArr[0]) {
$('#zipcode-error').html(result).show("slow");
}
else {
//show your hidden div here
$("#urHidden").show("slow");
}
});
});
When the return of the post is empty you will show the div
echo "<div id='city_holder'>No City</div>";
if(isset($_POST['zipcode'])){
$zip = $_POST['zipcode'];
if(empty($zip)){
echo "*Zipcode required!";
}elseif( (strlen($zip)<5) OR (strlen($zip)>5)){
echo "*Must be 5 digit!";
}elseif(!is_numeric($zip)){
echo "Must be numeric!";
}else{
$query = mysql_query("SELECT * FROM zip_codes WHERE zip = '{$zip}'");
$found_zip = mysql_num_rows($query);
if($found_zip =1){
$row = mysql_fetch_array($query);
echo "<div id='city_holder'>".$row['city_name']."</div>";
echo "<img src='images/check.jpg' /><input type = 'hidden' name='show-city' id='show-city' />";
} else{
echo "Zip not found";
}
}
}
$('#zipcode').keyup(function() {
$.post('action/validate_signup.php?key=zipcode', { zipcode: $(this).val() },
function(result){
if($('#city_holder').html() != 'No City')
{
$('#city').val($('#city_holder').html()); //to fill up the input
$('#city-wrapper').show("slow");//to show the div
}
else{
$('#city').val(" "); //to empty the input
$('#city-wrapper').hide("slow");//to hide the div
$('#zipcode-error').html(result).show("slow");
}
});
});
Hope it helps you
Don't forget to set the city_holder to hidden with your CSS
If you want any other help comment it

PHP - verify if user exist in DB and display the result without reloading the page

I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you
HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>
<p><input class="signup_button" type="submit" value="inregistrare">
</form>
<div class="clear"></div>
</div>
register.php
<?php
include "base.php";
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$pass = 1;
$alert .="<li>" . $usertaken . "</li>";
}
else
{
$registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
if($pass == 1) {
echo '<script>$(".message").hide("").show(""); </script>';
echo "<ul>";
echo $alert;
echo "</ul>";
}
}
?>
SOLUTION (add this in head and hide .message div)
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#alert',
beforeSubmit: showRequest,
success: showResponse
};
$('#signup_form').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText) {
}
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
You need to use AJAX to do a dynamic page update.
Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.
Your current code uses a form submit, which always reloads the page.
You need to use ajax. Write something like this as a JavaScript:
var xmlHttp;
function checkUser(user) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request.");
return;
}
var url = "check.php"; //This is where your dynamic PHP file goes
url = url + "?u=" + user;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = getData;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function getData () {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if (xmlHttp.responseText == 1) {
alert('Username free'); //action if username free
} else {
alert('This username is taken'); //action if its not
}
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.
EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.
If that's all in a single page, you'll have to structure it like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do form retrieval/database stuff here ...
if (error) {
$message = 'Something dun gone boom';
}
}
if ($message != '') {
echo $message;
}
?>
form stuff goes here

Categories