Call us Toll-Free:
1-800-218-1525
Email us

jQuery for Real time Server-side Form Validation

Dawn Rossi, July 17    --    Filed under Programming
jQuery is a JavaScript Library that includes document traversing, drag&drop, date picker, tabs animating, and Ajax interactions for rapid web development. It's widely deployed and used by Google, Digg, Mozilla as well as many other huge sites.

As part of this post, I'll demonstrate how to use jQuery for real time server-side form validation.

The Challenge

Most HTML forms use simple Javascript to validate user input, before the form is submitted to the server.

A javascript function runs inside the browser and validates that a date field is valid, a username field doesn't contain invalid characters etc.

Providing user input passes these simple client-side validation tests, the form is submitted to the server, where the server performs additional validations on the entered data.

Some examples where this approach is lacking:

* A username may be valid on the client side, but already taken by the time the form is submitted.

* Information on the server-end is required to validate a password

* USPS lookup is necessary to validate an address / zip code etc.

jQuery

Since data on the server side is required for some validations, we need a way to ping the server and validate fields as the user is typing text in the form.

jQuery to the rescue!

Start by including jQuery in your html code:


<script type="text/javascript" src="https://softwareprojects.com/script/jquery.js"></script>

Designating a field as required is easy - simply add a hidden input tag with the name of require_FIELDNAME:


Enter your name
: <input name=fullname type=text>
<
input type=hidden name=require_fullname>

Integrating server-side validation with a form field and displaying an error message if validation fails, can be done with a single call:




$(document).ready(function () {
  $(
'#username').bind('blur',function(e){
    $.
get("/validate_username.php", {login: $(this).val()}, function(data){
      $(
'#username_message').html(data);
    },
'html');
  });
});

Complete Example

This example features server-side validation of a password and username (check for invalid characters and verify username is available), displaying an inline error message if validation fails.

Here's how the end result looks like:



HTML code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>jQuery Demo</title>

<
link rel="stylesheet" href="style2.css" type="text/css" media="screen" />
<
script type="text/javascript" src="https://softwareprojects.com/script/jquery.js"></script>
<script language="javascript">
<!--
$.ajaxSetup ({
  cache: false
});
// Validate subdomain using validateusername.php
// Display result into s_dom div tag
$(document).ready(function () {
  $('#subdomain').bind('blur',function(e){
    $.get("/validateusername.php", {login: $(this).val()}, function(data){
      $('#s_dom').html(data);
    }, 'html');
  });

// Validate password using validatepassword.php
// Display result into s_password div tag
  $('#password').bind('blur',function(e){
    $.get("/validatepassword.php", {password: $(this).val()}, function(data){
      $('#s_password').html(data);
    }, 'html');
  });

// Validate password2 using validatepassword.php
// Display result into s_password2 div tag
  $('#password2').bind('blur',function(e){
    $.get("/validatepassword.php", {password: $(this).val()}, function(data){
      $('#s_password2').html(data);
    }, 'html');
  });
});

//-->
</script>
</head>
<body>


<div id="page">
 
  <!--main start-->
  <div class="main">
 
    <div class="rbody">
    <div >
        <div class="roundbodytop">
          <div class="innerbody">
            <div class="leftside3">
           
            <p align="center"><img src="copy/images/homebusinessprofitblueprint2.png" width="694" height="82" /></p>
            <p align="center" class="mainRedTitle"></p>
            <p align="center"> <span class="mainRedTitle"><strong>Congratulations
              <?=$name?>! Your Account Is Now Active. The Final Step Is To Personalize Your System Information Below.</strong></span>
             
            </p>
            <p align="center" class="blacktitle"><strong>Please
              choose a password and system subdomain below.*
              The subdomain will be part of your personal link to
              your system.* </strong></p>
             
           
            <p>*</p>
           
            <form id="form1" name="form1" method="post" action="thankyou1.php">
              <table width="100%" border="0" cellpadding="0">
              <tr>
                <td width="22%"><div align="right" class="text14"><strong>System Details</strong></div></td>
                <td width="78%">*</td>
              </tr>
              <tr>
                <th><span class="red">*</span> Password :</th>
                <td><input name="password" type="password" class="InputBoxFront" size="40" maxlength="100" id="password" />
                <span class="red" id="s_password"><? if (isset($_POST['save'])) {
                    if (
$_POST['password']== '') {
                      echo
"This field must be filled in";
                     
$all_ok=false
                    }
                  }
?></span>                </td>
              </tr>
              <tr>
                <th><span class="red">*</span> Password verification :</th>
                <td><input name="password2" type="password" class="InputBoxFront" size="40" maxlength="100" id="password2" /> <span class="red" id="s_password2"></span>
               
                <span class="red"><? if (isset($_POST['save'])) {
                    if (
$_POST['password2']== '') {
                      echo
"This field must be filled in";
                     
$all_ok=false
                    } else {
                      if (
$_POST['password2'] != $_POST['password']) {
                        echo
"Passwords must match";
                       
$all_ok=false
                      }
                    }
                  }
?></span>              </td>
              </tr>
              <tr>
                <th><span class="red">*</span> System subdomain choice :</th>
                <td><input name="subdomain" type="text" class="InputBoxFront" size="10" maxlength="100" id="subdomain" />
                .homebusinessprofitblueprint.com
                <span class="red"><? if (isset($_POST['save'])) {
                    if (
$_POST['subdomain']== '') {
                      echo
"This field must be filled in";
                     
$all_ok=false
                    }
                  }
?></span><div id="s_dom" class="red"></div>                  </td>
              </tr>
             
              <tr>
                <td colspan="2" align="center">*</td>
              </tr>
              <tr>
                <td colspan="2" align="center"><div align="center">
                <a href="javascript:OnUpdate();"><img src="images/homebut3.png" border="0" /></a>
                </div></td>
              </tr>
              </table>
            </form>
            <p>*</p>
            <p>*</p>
          </div>
           
           
        </div>
       
        </div>
       
      </div>
    </div>
    <SCRIPT>
function OnUpdate()
{
  // Basic Javascript validation
  if (document.getElementById('form1').password.value=="")
  {
    alert("Password is required");
    return;
  }
  if (document.getElementById('form1').password2.value=="")
  {
    alert("Please repeat the password");
    return;
  }
  if (document.getElementById('form1').subdomain.value=="")
  {
    alert("Subdomain is required");
    return;
  }
  if (document.getElementById('form1').password.value!=
document.getElementById('form1').password2.value)
  {
    alert("The passwords should be the same");
    return;
  }

  // Server-side validation
  // Username
  $.get("/validateusername.php", {login: $('#subdomain').val()}, function(data)
  {
    if (data!="")
    {
      alert("Invalid subdomain");
      return;
    }
  }, 'html');
  // Password
  $.get("/validatepassword.php", {password: $('#password').val()}, function(data)
  {
    if (data!="")
    {
      alert("Invalid password");
      return;
    }
  }, 'html');;
 
 
  document.getElementById('form1').submit();
}
</SCRIPT>

The validateusername.php file:


// Connect to your database
mysql_connect("host","username","password");

// Check if we already have a customer with this username
$Result = mysql_query("SELECT * FROM customers where login='".mysql_real_escape_string($login)."' limit 1");       
if (!empty(
$login) && $login != 'www')
{
  if (
mysql_num_rows($Result)>0)
  {
    echo
"Username already exists";
  }
  else
  if (
preg_match("/[^A-Za-z0-9_-]/",$login))
  {
    echo
"Invalid username. Please only use A-Z, a-z and 0-9 characters";
  }
}
else
{
  echo
'Incorrect username';
}

The validatepassword.php file:


 
if (preg_match("/[^A-Za-z0-9_-!]/",$password))
  {
    echo
'Invalid password. Please only use A-Z, a-z, 0-9, "-" or "!"';
  }


View 3 Comment(s)

How to manually process MySQL replication log files

Mike Peters, July 15    --    Filed under Programming
MySQL replication log files are simple text files, with a dump of all queries issued on the designated server.

At certain times, when MySQL slave servers fall behind, it may be useful to copy the log files over from the master to the slave machines and then manually process them.

To process a MySQL replication log file, copy the file from the master to the slave machine, then issue this command:

mysqlbinlog /usr/tmp/mysql-bin.000001 --start-position=1234 | sed -e 's/SET \/\*\!\*\//SET AUTOCOMMIT=0/g' | mysql -uUSERNAME -pPASSWORD

Replace 1234 with the last position the slave was able to read
Replace mysql-bin.000001 with the master file name
And replace USERNAME/PASSWORD with the slave database credentials

Mailing Lists and Segments

Mike Peters, July 10    --    Filed under SoftwareProjects Products
SPI Email Marketing system supports two types of destination lists:

* Static Mailing List

Add an unlimited number of custom fields, import lists from your machine or a remote server.

The number of recipients on these type of lists always stays the same, until people unsubscribe or you import new records.

See this short video for a walk-through of how to import emails to a list.

* List Segment

A list segment is a powerful filter on your entire database. It's a database SQL rule, that allows you to create tightly focused groups of customers, leads or affiliates.

For example, you can create a segment of "All customers whose payment got declined over the last 7 days", or "All customers residing in New York who purchased Product X" etc.



-

Your SPI account manager will create several popular list segments in your account: All customers, All affiliates, All leads etc.

You can add as many segments as you need. Use list segments wisely to tailor specific messages to targeted groups of customers.

List segments are updated several times every day, applying the SQL-rule on your entire database, to filter-in the records that belong to each segment.

Sending email broadcasts

Once your mailing lists and segments are defined, sending out a broadcast is a breeze.

Simply click 'Send Broadcast', type-up your message and select the target list or lists.





The system will automatically de-dup, so that no recipient ever receives the same message more than once.

A note about Autoresponders

Every autoresponder you create under the Autoresponder service, will automatically create a list-segment in the Email Marketing service:



This way, you can broadcast messages on-demand, to all subscribers of an individual autoresponder.

Affiliate System Commission Plans setup

Mike Peters, July 9    --    Filed under SoftwareProjects Products
The SPI Affiliate System supports two types of commission plans:

Product Commission Plan

Pay affiliate X per every sale of the designated product

Affiliate Commission Plan

Pay affiliate X per every product sale that doesn't have its own specific commission plan assigned to it

-

You can think of it as the 'Affiliate Commission Plan' being the default pay, while the 'Product Commission Plan' allows applying specific rules to individual products.

For example, let's say you'd like to pay a certain affiliate 30% on all the sales they generate, except for the "Red Widgets" product where you have lower margin. On that product, you want the affiliate to be paid 10%.

You would create two commission plans: a 10% one and a 30% one.

Assign the 30% commission plan to the affiliate:



And assign the 10% commission plan to the individual product:



The affiliate will be credited as soon as the referred customer is charged.

Once you define commission plans, you can associate the same commission plans to multiple affiliates / products.

-

Now let's go over all the options you have when setting up a new commission plan:



You can define different rules for the 'First Payment' vs 'Recurring orders'.

In the example above we're paying affiliates 20% on all sales plus a flat $5.00 fee and the same rules apply for recurring payments.

We're also paying $2 per every lead generated.

The 'Keep Paying until' section, allows you to control whether you'd like to keep paying affiliates for the life-cycle of the customer, or limit the number of pay cycles.

The 'Override' flag is useful when you have an affiliate where you'd like them to be paid a certain amount/percentage, regardless of any product-defined commission plans. This is typically used with partners.

Email Marketing Tracking Domain

Mike Peters, July 9    --    Filed under SoftwareProjects Products
Whenever you send an email broadcast / autoresponder or system-message with SPI, your emails are delivered via dedicated ip-addresses.

As part of our ongoing effort to optimize delivery rates, in addition to using dedicated ip addresses, we also dynamically update all the links in your email messages to use a custom tracking domain.



For example, the following email message:

Quote:
Hi {%firstname%},

Please visit www.somedomain.com for more information about our program.

Sincerely,
John Doe, Company Name
www.mywebsite.com

will be converted to -

Quote:
Hi {%firstname%},

Please visit www.spilnk.com/CODE1 for more information about our program.

Sincerely,
John Doe, Company Name
www.spilnk.com/CODE2

All links in the message body are automatically replaced with the tracking-domain, so that your message contains outgoing links to a single domain, which we manage the email-reputation for.

You can use your main website domain-name for tracking, or you can register a new generic domain.

To setup your own tracking domain, use one of two options:

Redirecting an entire domain

Setup your domain to redirect to spilnk.com, or point it to this IP address: 174.36.170.90

Using a sub-folder under your primary website domain

Create a new directory under your website and call it 'r' (short for redirect)

Place this index.php file under that directory:


$url
= substr($REQUEST_URI,2);
Header("Location: http://spilnk.com$url");

Now update your web server config file, to redirect all 404's under /r to index.php

If you're using NGinx, this setup will do the trick:


  server
{
   
listen  1.2.3.4:80;
   
server_name www.mydomain.com *.mydomain.com;
 
   
# set regular docroot
   
location /
    {
     
root /home/mydomain.com/htdocs/;
     
index index.php index.html index.htm;

     
error_page 404 = /index.php;
    }

   
location ~* .(php)$
    {
     
fastcgi_intercept_errors on;
     
     
error_page 404 = /r/index.php;

     
fastcgi_pass backend;
     
fastcgi_index index.php;
     
fastcgi_param SCRIPT_FILENAME /home/mydomain.com/htdocs/$fastcgi_script_name;
      include    /
etc/nginx/fastcgi_top.conf;
     
fastcgi_param DOCUMENT_ROOT  /home/mydomain.com/htdocs/;
      include    /
etc/nginx/fastcgi_bottom.conf;
    }
 
   
location /r
   
{
     
root /home/mydomain.com/htdocs/r/;
     
index index.php;
     
     
error_page 404 = /index.php;
     
     
fastcgi_pass backend;
     
fastcgi_index index.php;
     
fastcgi_param SCRIPT_FILENAME /home/mydomain.com/htdocs/r/index.php;
      include    /
etc/nginx/fastcgi_top.conf;
     
fastcgi_param DOCUMENT_ROOT  /home/mydomain.com/htdocs/;
      include    /
etc/nginx/fastcgi_bottom.conf;
    }
  }

NGinx html files as php

Dawn Rossi, July 9    --    Filed under Programming
A typical NGinx config file follows this format:


upstream backend
{
 
server unix:/tmp/fastcgi.sock;
 
server 127.0.0.1:88 backup;
}

 
server
 
{
   
listen  1.2.3.4:80;
   
server_name www.domain.com *.domain.com;
   
server_name_in_redirect off;

   
# set regular docroot
   
location /
    {
     
root /home/domain.com/;
     
index index.php index.html index.htm;
    }

   
location ~ .php$
    {
     
fastcgi_pass backend;
     
fastcgi_index index.php;
     
fastcgi_param SCRIPT_FILENAME /home/domain.com/$fastcgi_script_name;
      include    /
etc/nginx/fastcgi_top.conf;
     
fastcgi_param DOCUMENT_ROOT  /home/domain.com/;
      include    /
etc/nginx/fastcgi_bottom.conf;
    } 
  }

Such a setup tells NGinx to serve all files normally, but pass *.php files to FastiCGI.

At times you may want to treat html files as php. To do so, we simply have to tell NGinx to pass *.php, *.htm and *.html files to FastCGI:


  server
 
{
   
listen  1.2.3.4:80;
   
server_name www.domain.com *.domain.com;
   
server_name_in_redirect off;

   
# set regular docroot
   
location /
    {
     
root /home/domain.com/;
     
index index.php index.html index.htm;
    }

   
location ~* .(htm|html)$
    {
     
fastcgi_pass backend;
     
fastcgi_index index.php;
     
fastcgi_param SCRIPT_FILENAME /home/domain.com/$fastcgi_script_name;
      include    /
etc/nginx/fastcgi_top.conf;
     
fastcgi_param DOCUMENT_ROOT  /home/domain.com/;
      include    /
etc/nginx/fastcgi_bottom.conf;
    } 
  }

We recently had to configure NGinx to support a WordPress site where -

* html files are processed as php
* 404 (not found) *.html files are passed to WordPress (for the clean-urls plugin)
* All other 404's are passed to a php notfound script

This was a little tricky to setup, but we finally came up with this config:


  server
 
{
   
listen  1.2.3.4:80;
   
server_name www.domain.com *.domain.com;

   
server_name_in_redirect off;

   
# set regular docroot
   
location /
    {
     
root /home/domain.com/public_html/;
     
index index.php index.html index.htm;

     
error_page 404 = /blog/notfound.php;
    }

   
location /blog/
    {
     
root /home/domain.com/public_html/;
     
index index.php;
     
     
error_page 404 = /blog/notfound.php;
    }
   
   
location ~* .(php)$
    {
     
fastcgi_pass backend;
     
fastcgi_index index.php;
     
fastcgi_param SCRIPT_FILENAME /home/domain.com/public_html/$fastcgi_script_name;
      include    /
etc/nginx/fastcgi_top.conf;
     
fastcgi_param DOCUMENT_ROOT  /home/domain.com/public_html/;
      include    /
etc/nginx/fastcgi_bottom.conf;

     
error_page 404 = /notfound.php;
    }

   
location ~* .(htm|html)$
    {
     
fastcgi_pass backend;
     
fastcgi_index index.php;
     
fastcgi_param SCRIPT_FILENAME /home/domain.com/public_html/notfound.php;
      include    /
etc/nginx/fastcgi_top.conf;
     
fastcgi_param DOCUMENT_ROOT  /home/domain.com/public_html/;
      include    /
etc/nginx/fastcgi_bottom.conf;

     
error_page 404 = /notfound.php;
    }

  }

The /notfound.php file:


if (file_exists($DOCUMENT_ROOT.$PHP_SELF))
{
require_once(
$DOCUMENT_ROOT.$PHP_SELF);
}
else
{
if (
strstr($PHP_SELF,"/blog"))
{
chdir($DOCUMENT_ROOT."/blog");
require_once(
$DOCUMENT_ROOT."/blog/notfound.php");
}
else
{
Header("Location: /blog/notfound.php");
}
}

And the /blog/notfound.php file:


Header
("HTTP/1.0 200 OK");

$p = $GLOBALS['REQUEST_URI'] = $_SERVER['REQUEST_URI'] = $REQUEST_URI = str_replace(array("%scategory%","/blog"),array("",""),$REQUEST_URI);
require_once(
$DOCUMENT_ROOT."/blog/index.php");


View 3 Comment(s)
« Previous Posts » Next Posts



About Us  |  Contact us  |  Privacy Policy  |  Terms & Conditions