JavaScript Form Validation

WHY CLIENT SIDE FORM VALIDATION???
Forms validation on the client-side is essential — it saves time and bandwidth, and gives you more options to point out to the user where they’ve gone wrong in filling out the form. But apart from this you should also use server side validation. because people visit your site may use an old browser or have JavaScript disabled, which will break client-only validation. Client and server-side validation complement each other, and as such, they really shouldn’t be used independently.

WHY IS CLIENT SIDE FORM VALIDATION IS GOOD?
It’s a fast form of validation: If something’s wrong, the event is triggered upon submission of the form or on change of focus.
You can safely display only one error at a time and focus on the wrong field, to help ensure that the user correctly fills in all the details you need.

The two key approaches to client-side form validation are:
1- Display the errors one by one, focusing on the offending field.
2- Display all errors simultaneously, server-side validation style.

While displaying all errors simultaneously is required for server-side validation, the better method for validation on the client-side is to show one error at a time. This makes it possible to highlight only the field that has been incorrectly completed, which in turn makes revising and successfully submitting the form much easier for the visitor. If you present users with all errors at the same time, most people will try to remember and correct them at once, instead of attempting to re-submit after each correction.
Here is the HTML code for the form validation:-
<html> <head> <title>Java script form validation</title> <script type=”text/javascript”> function form_validate() { if( document.Form.Name.value == “” ) { alert( “Please enter your first name.” ); document.Form.Name.focus() ; return false; } if( document.Form.EMail.value == “” ) { alert( “Please enter your E-mail address.” ); document.Form.EMail.focus() ; return false; } if( document.Form.Zip.value == “” || isNaN( document.Form.Zip.value ) || document.Form.Zip.value.length != 5 ) { alert( “Please enter a zip in the format *****.” ); document.Form.Zip.focus() ; return false; } } </script> </head> <body> <form name=”Form” onsubmit=”return(form_validate());”> <table> <tr> <td>First Name:</td> <td><input type=”text” name=”Name” /></td> </tr> <tr> <td>E-Mail Address:</td> <td><input type=”text” name=”EMail” /></td> </tr> <tr> <td>Postal Code:</td> <td><input type=”text” name=”Zip” /></td> </tr> <tr> <td></td> <td><input type=”submit” value=”Submit” /></td> </tr> </table> </form> </body> </html>

Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

JavaScript Email validation Using Regular Expression

In this tutorial of Php Point we will show you a simple way of validating email address using javascript and Regular Expression

It is the simple code to help you in creating a form with email validation using regular expression.
<html>
    <head>
        <title>JavaScript form validation Using regular expression</title>
        <script type= “text/javascript”>
            function Validate(input)
            {
                var format = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
                if(document.getElementById(“email”).value.match(format))
                {
                    document.myform.email.focus();
                    return true;
                }
                else
                {
                    alert(“You have entered an wrong email address!”);
                    document.myform.email.focus();
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <h2>Input an email and Submit</h2>
        <form name=”myform” action=”#”>
            <input type=’text’ name=’email’ id=”email”/>
            <input type=”submit” name=”submit” value=”Submit”   onclick=”Validate(document.myform.email)”/>
        </form>
    </body>
</html>
Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Some Basic But Useful WordPress Functions

In this tutorial of PHP Point we will show you some basic but important functions of WordPress.

Here is the list of top 10 functions which are commonly used during wordpress website development.

1 – $current_category = single_cat_title(“”, false);
Display current category Title.
2 – $permalink = get_permalink( $id ); 
Returns the permalink to a post or page for use in PHP. 

3 – $cat_id = get_cat_ID( $cat_name ) ;
Retrieve the ID of a category from its name.

4 – $current_user = wp_get_current_user(); 
Retrieve the current user object.

5 – $current_user_id = get_current_user_id( ); 
Returns the ID of the current viewer if they are logged in. Returns 0 if the viewer is not logged in.

6 – $title = get_the_title();
Return the current post/page title.

7 – $posts = get_posts( array(‘numberposts’ => 6,’orderby’ => ‘post_date’,’order’ => ‘DESC’,’post_type’ => ‘post’,’post_status’ => ‘publish’ ) );
Get the posts from database according to the argument passed in it.

8 – get_header();
Add Header page to the file.

9 – bloginfo(‘home’);
Fetch the URL of your home page.

10 - the_content();
Displays the contents of the current post. This template tag must be within the loop.
Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Jquery Ajax File Upload Example in Php

In current world while making website or an application, the file uploading is one of the important requirement through front end or back end(Admin panel). Jquery and Ajax moved web development to the next level. Today no one want to upload files through traditional fashion or wait till page get reloaded completely after upload.
So here we will show you how to create your Jquery Ajax file upload application in php so that you don’t need to wait for page reload.
Jquery Ajax File Upload in Php
Jquery Ajax File Upload in Php
Here is the Download link for “Jquery Ajax File Upload in Php Tutorial”.



Creating Jquery Ajax file upload in php require 2 step procedure.

Step 1:- You need to create “index.html” file which contain code of front end to upload your files.
<html>
<head> <title>jQuery Ajax File Upload Example in PHP – Demo</title> <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js”></script> <script src=”http://malsup.github.com/jquery.form.js”></script> <link rel=”stylesheet” type=”text/css” href=”style.css” /> <script> $(document).ready(function() { var options = { target: ‘#message’, beforeSubmit: function() { $(“#progress”).show(); $(“#bar”).width(’0%’); $(“#message”).html(“”); $(“#percent”).html(“0%”); if (window.File && window.FileReader && window.FileList && window.Blob) { if( !$(‘#ajaxUpload’).val()) //check empty input filed { $(“#message”).html(“<font color=’red’>Please select the file to upload!!!</font>”); return false; } var fileSize = $(‘#ajaxUpload’)[0].files[0].size; //get file size var fileType = $(‘#ajaxUpload’)[0].files[0].type; // get file type //allow file types switch(fileType) { case ‘image/png’: case ‘image/gif’: case ‘image/jpeg’: case ‘image/pjpeg’: case ‘text/plain’: case ‘text/html’: case ‘application/x-zip-compressed’: case ‘application/pdf’: case ‘application/msword’: case ‘application/vnd.ms-excel’: case ‘video/mp4′: break; default: $(“#message”).html(“<font color=’red’><b>”+fileType+”</b> Unsupported file type!</font>”); return false } //Allowed file size is less than 5 MB (1048576) if(fileSize>5242880) { $(“#message”).html(“<font color=’red’><b>Too big file!</b> <br />File should be less than 5 MB.</font>”); return false; } $(“#message”).html(“”); } else { //Output error to older unsupported browsers that doesn’t support HTML5 File API $(“#message”).html(“Please upgrade your browser, because your current browser lacks some new features we need!”); return false; } }, uploadProgress: function(event, position, total, percentComplete) { $(“#bar”).width(percentComplete+’%’); $(“#percent”).html(percentComplete+’%’); }, success: function() { $(“#bar”).width(’100%’); $(“#percent”).html(’100%’); }, complete: function(response) { $(“#message”).html(“<font color=’green’>”+response.responseText+”</font>”); }, error: function() { $(“#message”).html(“<font color=’red’> ERROR: unable to upload files</font>”); }, resetForm: true }; $(‘#jqueryAjaxForm’).submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); </script> </head> <body> <div class=”main-wrapper”> <form id=”jqueryAjaxForm” name=”jqueryAjaxForm” action=”upload.php” method=”post” enctype=”multipart/form-data”> <h1 class=”page_header”>Jquery Ajax File Upload Example</h1> <input type=”file” size=”60″ name=”ajaxUpload” id=”ajaxUpload”> <input type=”submit” value=”Upload” id=”submit-btn”> </form> <div id=”progress”> <div id=”bar”></div> <div id=”percent”>0%</div > </div> <div id=”message” class=”msg”></div> </div> <br/> </body> </html>
Step 2:- In this step create a “upload.php” file which contain codes to move your file from temporary directory to specified directory.
<?php

    //In below line we are specifying the path/name of folder where uploaded image get stored.

    $output_dir = “uploads/”;

    if (isset($_FILES["ajaxUpload"])) {

        if ($_FILES["ajaxUpload"]["error"] > 0) {

            echo “Error Occured: ” . $_FILES["file"]["error"] . “<br>”;

        } else {

    //Below we are moving uploaded file from temporary directory to specified directory.

            move_uploaded_file($_FILES["ajaxUpload"]["tmp_name"], $output_dir . $_FILES["ajaxUpload"]["name"]);

            echo $_FILES["ajaxUpload"]["name"].” Successfully Uploaded.”;

        }

    }

?>
Thats it. No need to do any extra stuff now and your Jquery Ajax file upload application is ready to use.

Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Simple jQuery Ajax Comment System in Php

Simple jQuery Ajax Comment System in Php
Simple jQuery Ajax Comment System in Php
It looks very annoying when we submit comment and wait till the whole page gets load to check our comments added successfully. But what if don’t want to refresh/reload the page after submitting our comments? Here the solution is jQuery Ajax comment box. 
In this tutorial of PHP Tutorials for Beginners I will show you how to create Comment box without refreshing page with jQuery Ajax and Php. We will use jQuery Ajax for comment system so that the page will not refresh while adding or updating comment.

Please follow step by step to create jQuery Ajax Comment box with Php. 

Step 1:- First step is to create a table in you database. We have create as "comments" table in our example.

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `post_id` int(5) NOT NULL,
  `name` varchar(20) NOT NULL,
  `email` varchar(10) NOT NULL,
  `comment` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
Step 2:- Next step is to create our config.php file which will contain your database connection code.
<?php $database = “practice”; // the name of the database. $server = “localhost”; // server to connect to. $db_user = “root”; // mysql username to access the database with. $db_pass = “”; // mysql password to access the database with. $table = “comments”; // the table that this script will set up and use. $link = mysql_connect($server, $db_user, $db_pass); mysql_select_db($database, $link); ?>
Step 3:- Now the next step is to create an index.php page which contain your Front end Comment box code.
<script type=”text/javascript” src=”jquery.js”></script>
<script type=”text/javascript” src=”common.js”></script>
<link rel=”stylesheet” type=”text/css” href=”style.css” />
<?php
/* Including database connection file. */
include(‘config.php’);
session_start();
/*
  The below SESSION is very important step.
  Here we have stored post id into session,
  which is used while inserting and fetchig data from database.
  I have used static id ie “1″. So please replace this with your POST ID.
 */
$_SESSION['postid'] = 1;
?>

<!–
The below “Write Your Comment” link will use to show Ajax Comment Box on clicking on it.
–>
<h3 class=”comment form-signin”><a href=”#” onclick = “show_comment_box();”>Write Your Comments</a></h3>

<!–
The below div will show the Ajax Comment Box.
Initially I have made Ajax Comment Box hidden.
If you want to show it on page load it self then remove the style=”display: none;” line from it.
–>
<div class=”comment_box container login form-signin” style=”display: none;”>
     <div>
        <div>
            <input type=”text” class = “name” value=”Enter your name” name=”” onblur=”if(this.value == ”){this.value =’Enter your name’}” onfocus=”if(this.value == ‘Enter your name’) {this.value=”}” />
        </div>
        <div>
            <input type=”text” class = “email” value=”Enter your email” name=”” onblur=”if(this.value == ”){this.value =’Enter your email’}” onfocus=”if(this.value == ‘Enter your email’) {this.value=”}” />
        </div>
        <textarea onblur=”if(this.value == ”){this.value =’Enter your comment’}” onfocus=”if(this.value == ‘Enter your comment’) {this.value=”}”  class = “user_comment”  rows=”5″ cols=”60″ name=””>Enter your comment</textarea>
    </div>
    <span><a onclick=”submit_review()” href=”javascript:void(0)” class=”btn btn-large btn-primary”>Submit</a></span> |
    <span><a onclick=”cancel()” href=”javascript:void(0)” class=”btn btn-large btn-primary”>Cancel</a></span>
    <input type=”hidden” id=”post_id” value=”<?php echo $_SESSION['postid']; ?>” />
</div>

<!–
The below div will show the successful message after comment is added into database.
–>
<div class=”message”></div>

<!–
The below div will show the list of all comments for that perticular post.
–>
<div class=”comment_list form-signin”>
     <h3>User’s Comment on this Article:-</h3>
         <?php
         $query = “SELECT * FROM comments where post_id = ”.$_SESSION['postid'];
         $result = mysql_query($query);
         while ($res = mysql_fetch_array($result)) {
             ?>
        <label style=”font-size:18″>Name:-<?php echo $res['name']; ?></label>
        <label>Comment:-<?php echo $res['comment']; ?></label><br>
<?php } ?>
</div>
Step 4:- Now the next step is to make "common.js" page which we have included in index.php. This file contain all the functions and ajax request which are called while commenting.
function show_comment_box(){
        $(“.comment_box”).show();
    }

    function submit_review(){
        /*
        In below code we have first stored the values of post id,name,email and comment in some varialbles.
         */
        var id = $(‘#post_id’).val();
        var name = $(‘.name’).val();
        var email = $(‘.email’).val();
        var comment = $(‘.user_comment’).val();
        /*
        In below code we checking if user have entered all feilds or not?
         */
        if(comment != “Enter your comment” && name != “Enter your name” && email != “Enter your email”){
            $(‘body’).css(‘cursor’, ‘progress’);
          /*
            In below code we are passing the data to external url which contain the code to add our inputs into database.
           */
            $.ajax({
                type: “POST”,
                url: “http://localhost/ajax_comment_box/add_comment.php”,
                data: { pid:id,user_name:name, user_email:email, user_comment:comment}
            }).done(function( result ) {
                setTimeout( function(){
                    if(result == “”){
                        $(“.message”).html(“Your comment is added successfully.”);
                        $(‘.comment_list’).fadeOut([30]).load(‘http://localhost/ajax_comment_box/reload_comment.php’).fadeIn([10]);
                        $(“.name”).val(‘Enter your name’);
                        $(“.email”).val(‘Enter your email’);
                        $(“.user_comment”).val(‘Enter your comment’);
                        $(“.comment_box”).hide();
                        $(‘body’).css(‘cursor’, ‘auto’);
                    }
                }, 2000);
            });
        }else{
            alert(“Please fill all the field!!!”);
        }
    }

    function cancel(){
        $(“.comment_box”).hide();
        $(“.name”).val(‘Enter your name’);
        $(“.email”).val(‘Enter your email’);
        $(“.user_comment”).val(‘Enter your comment’);
    }
Step 5:- This is the second last step while creating jQuery Ajax Comment Box. In this step we will create file called "add_comment.php". This file will be called when ajax request is made after submitting comment and it will insert the data into database.
<?php
    include(‘config.php’);
    $post_id = $_POST['pid'];
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $comment = $_POST['user_comment'];
    $query = “INSERT INTO comments(post_id, name, email, comment) VALUES(‘$post_id ’,’$name ’,’$email ’,’$comment’)”;
    mysql_query($query) or die (“MySQL Error.”);
?>
Step 6:- This is the last step of jQuery Ajax Comment Box. In this step we will create file called "reload_comment.php". After successful data insertion we need to update the comment list, so "reload_comment.php" will be called at that time and it will update the comments without refreshing the page.
<?php
    session_start();
    include(“config.php”);
    $query = “SELECT * FROM comments where post_id=”.$_SESSION['postid'];
    $result = mysql_query($query);
    while($res=mysql_fetch_array($result)){ ?>
    <div style=”font-size:18″>Name:-<?php echo $res['name']; ?></div>
    <div>Comment:-<?php echo $res['comment']; ?></div><br>
<?php } ?>
Hope this php tutorial is useful for you. Keep following Php Point for more examples.
Continue Reading