Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, June 6, 2013

AJAX - Parse XML result

In previous example, we got response as plain text.
//
document.getElementById("result").innerHTML = xmlhttp.responseText;
//

Today, we would like to get and parse XML response with AJAX.
See employee.xml

    
        Mike
        20
        mac
        iphone
        ipad
    
    
        James
        25
        mac
        iphone
        ipad
    
    
        Judy
        18
        mac
        iphone
        ipad
    



AJAX code
function getResult() {
    var xmlhttp = new XMLHttpRequest();
    var name = document.getElementById("name").value;
    
    xmlhttp.onreadystatechange = function() {   
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // get root element
            var root = xmlhttp.responseXML.documentElement;
            // get all employee emelemts
            var employees = root.getElementsByTagName("employee");
            var name = "";
            var age = undefined;

            var output = "";
            
            // get name and age for each employee element
            for (var i = 0; i < employees.length; i++) {
                name = employees[i].getElementsByTagName("name");
                age = employees[i].getElementsByTagName("age");
                output += name[0].firstChild.data + " is " + age[0].firstChild.data + ".";
            }
     
            document.getElementById("result").innerHTML = output;
        }
    }
   
    xmlhttp.open("GET", "employee.xml");
    xmlhttp.send();
}


jQuery implementation
function getResult() {
    $.ajax({
        url: 'employee.xml',
        dataType: 'xml',
                
        success: function(data) {
            $('#result').text("");
            $(data).find('employees employee').each(function() {
                var name = $(this).find('name').text();
                var age = $(this).find('age').text();
                var id = $(this).attr('id');
                var asset = $(this).find('asset').eq(0).text();
                        
                $('#result').append(
                    $('<div />', {
                        text: '(' + id + ') ' + name + ' is ' + age +
                              ' - ' + asset + '.'
                    })
                );
            })
        },
                
        error: function() {
            $("#result").text("failed to load.");
        }
    });
}

Result




AJAX - Request MySQL data through PHP

Suppose we need to get password (actually hash value in database) of a specified user, how we can make that?

We have a form to get user name input and have a button associated with function getResult().
 

getResult()
function getResult() {
    var xmlhttp = new XMLHttpRequest();
    var name = document.getElementById("name").value;
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            setTimeout(function() {document.getElementById("result").innerHTML = xmlhttp.responseText;}, 1000);
        } else {
            document.getElementById("result").innerHTML = "Loading...";
        }
    }
   
    xmlhttp.open("POST", "getuserhash.php");
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("name=" + name);
}

getuserhash.php
include_once('connection.php');

$name = $_POST['name'];

$query = $pdo->prepare("SELECT user_password FROM user WHERE user_name = ?");
$query->bindValue(1, $name);
$query->execute();
$data = $query->fetch();

echo $data["user_password"];

It works!







Use jQuery to rewrite getResult()
        
function getResult() {
    var name = $("#name").val();
    $.post("getuserhash.php", {name:name}, 
        function(data) {
            $("#result").html(data);
        }
    );
}

Wednesday, June 5, 2013

AJAX - First Sample

AJAX, a.k.a Asynchronous JavaScript and XML. According to the name, we can feel it is not a new technology, but something JavaScript and XML related. AJAX is actually a new way of exchanging data using current standards. AJAX allows user to request only necessary data from the server and update the data on page, so we don't have to reload the whole page.

So let us see a simplest sample
    

    AJAX Sample




Several interesting things in above code.

XMLHttpRequest
It is used to send HTTP and HTTPS requests to the server and load response data. The data could be received from the server as JSON, XML, HTML or plain text. In our example, it is plain text.
xmlhttp.open
The requests must be initialized through the open method. It has five parameters in total (Method, URL, Asynchronous, UserName, Password) and only the first two are required. Supported methods could be GET, POST, HEAD, PUT, DELETE and OPTIONS. Asynchronous has two Boolean values, and true is the default one. False will block execution of the current script until the request has been completed, thus not invoking the onreadystatechange event listener.
xmlhttp.send
Send the request and you can specify a string data for and only for POST request.
xmlhttp.onreadystatechange
It is a event listener and will be automatically invoked when readyState property of the XMLHttpRequest object is changed.
xmlhttp.readyState
equals 1 after open has been invoked successfully
equals 2 after send has been invoked and response head has been received
equals 3 after response starts to load
equals 4 after response has finished loading
If you would like to see how the readyState is changed, try below code
    
if (xmlhttp.readyState == 1) {
    document.getElementById("result").innerHTML = xmlhttp.readyState;
} else if (xmlhttp.readyState == 2) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 2000);
} else if (xmlhttp.readyState == 3) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 4000);
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 6000);
    setTimeout(function() {document.getElementById("result").innerHTML = xmlhttp.responseText;}, 8000);
} else {
    document.getElementById("result").innerHTML = "Failed to load.";
}

Tuesday, June 4, 2013

PHP - Register User

In a-simple-cms, we don't have a page that allows to create new user. So we create this page now and use jQuery form validation plugin to validate the input before forwarding the request.

Now the admin login page is








We create a admin register link to the registration page










See the code of admin registration page
if (isset($_POST['name'], $_POST['pass1'])) {

    include_once('../includes/connection.php');
    include_once('../includes/chash.php');

    $chash = new CHash();

    $name = $_POST["name"];
    $password = $_POST["pass1"];
    $phash = $chash->generateHash($password);

    $query = $pdo->prepare("INSERT INTO user (user_name, user_password) VALUES (?, ?)");
    $query->bindValue(1, $name);
    $query->bindValue(2, $phash);

    if($query->execute()){
        echo "admin created!";
    } else {
        echo "creation failed.";
    }

} else {
    // display registration form
}

Include css, jQuery library, jQuery validation plug in and custom validation code.




Code of custom.js
$(document).ready(function() {
    $("#form").validate({
        rules: {
            name: {
                required: true,
                minlength: 5,
                maxlength: 20
            },

            pass1: {
                required: true,
                minlength: 8,
                maxlength: 30
            },

            pass2: {
                required: true,
                minlength: 8,
                maxlength: 30,
                equalTo: "#pass1"
            },

            username: {
                required: true
            },

            password: {
                required: true
            }
        }
    });
});


Registration form
Admin Registration

See the form check result










Create admin with name "admin"










Created






Admin entry created in database





Because user_name is primary key, so we cannot create another admin with "admin" again.






All right, now we can login with the admin created



Sunday, June 2, 2013

jQuery - Create custom rules for validation plugin

Suppose we need a strong password like that in post javascript-form-validation:
  • has lower and upper case
  • has digital
  • has special character
How we can do this with jQuery validation plugin?

Obviously, we need add our custom rules for the plugin and luckily, it is quite simple. - Use addMethod
  jQuery.validator.addMethod("hasLower", function(value, element) {
      return this.optional(element) || (element.value.match(/[a-z]/));
  }, "Must have lower case character.");
  
  jQuery.validator.addMethod("hasUpper", function(value, element) {
      return this.optional(element) || (element.value.match(/[A-Z]/));
  }, "Must have upper case character.");
  
  jQuery.validator.addMethod("hasDigital", function(value, element) {
      return this.optional(element) || (element.value.match(/\d+/));
  }, "Must have digital.");
  
  jQuery.validator.addMethod("hasSpecial", function(value, element) {
      return this.optional(element) || (element.value.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/));
  }, "Must have special character, such as !,@,#,$,%,^,&,*,?,_,~,-,(,).");

Now the password rule is like this
     pass1: {
         required: true,
         minlength: 8,
         maxlength: 30,
         hasLower: true,
         hasUpper: true,
         hasDigital: true,
         hasSpecial: true
     },

It works!








Saturday, June 1, 2013

jQuery - Validate form with jQuery validation plugin

What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. - jquery.com
What is jQuery validation plugin?
This jQuery plugin makes simple clientside form validation trivial, while offering lots of option for customization. That makes a good choice if you’re building something new from scratch, but also when you’re trying to integrate it into an existing application with lots of existing markup. The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 37 locales. - jquery-plugin-validation
See the code of the form and how it looks like
Register Form











How to call the validate?
$(document).ready(function() {
    $("#form").validate({
       //  
    });
});

We can add rules in validate, it is quite easy to understanding the function through the name.
    
rules: {
     name: {
         required: true,
         minlength: 5,
         maxlength: 20
     },
     
     pass1: {
         required: true,
         minlength: 8,
         maxlength: 30
     },
     
     pass2: {
         required: true,
         minlength: 8,
         maxlength: 30,
         equalTo: "#pass1"
     },
     
     email1: {
         required: true,
         email: true
     },
     
     email2: {
         required: true,
         email: true,
         equalTo: "#email1"
     }
    
},

Also, we can overwrite the error message
messages: {
     name: {
         required: "Please enter name.",
         minlength: "Minimum 5 characters.",
         maxlength: "Maximum 20 characters."
     },
     
     pass1: {
         required: "Please enter password.",
         minlength: "Minimum 8 chacters.",
         maxlength: "Maximum 30 characters."
     },
     
     pass2: {
         required: "Please enter password.",
         minlength: "Minimum 8 chacters.",
         maxlength: "Maximum 30 characters.",
         equalTo: "Inconsistent password."
     },
     
     email1: {
         required: "Please enter email.",
         email: "Please type a valid email."
     },
     
     email2: {
         required: "Please enter email.",
         email: "Please type a valid email.",
         equalTo: "Inconsistent email."
     }
}

So, when we input nothing and click register









Show some other error information

Thursday, May 30, 2013

JavaScript - Form Validation

JavaScript is frequently used in form validation before the request submitted to server. It saves bandwidth and time, and also greatly prompt user experience.

However, in some situation, you have to use server side validation
  • JavaScript is not available on the device
  • JavaScript is turned off by user
  • JavaScript is disabled by network administrator
But that is not our topic today. :)

So, how to validate a form with JavaScript?

Let us see how the form looks like
















Validation Code
function saveChanges() {
    var firstName = document.getElementById("firstName");
    var lastName = document.getElementById("lastName");
    var phoneNumber = document.getElementById("phoneNumber");
    var email = document.getElementById("email");
    var password = document.getElementById("password");

    var errMsg = "";

    if (firstName.value === "") {
     errMsg += "First Name is empty. \n";
     firstName.style.borderColor = "red";
    }

    if (lastName.value === "") {
     errMsg += "Last Name is empty. \n";
     lastName.style.borderColor = "red";
    }

    if (phoneNumber.value.length > 30) {
     errMsg += "Phone number is too long, maxium 30 characters. \n";
     phoneNumber.style.borderColor = "red";
    }
    
    if (!pattern.test(email.value)) {
     errMsg += "Not a valid email. \n";
     email.style.borderColor = "red";
    }

    if (password.value.length < 8) {
     errMsg += "Your password is too short, minimum 8 characters. \n";
     password.style.borderColor = "red";
    }

    if (!((password.value.match(/[a-z]/)) && (password.value.match(/[A-Z]/)))) {
     errMsg += "Your password should have both lower and uppercase characters. \n";
     password.style.borderColor = "red";
    }

    if (!password.value.match(/\d+/)) {
     errMsg += "Your password should have at least one number. \n";
     password.style.borderColor = "red";
    }

    if (!password.value.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) {
     errMsg += "Your password should have at least one special character. \n";
     password.style.borderColor = "red";
    }

    if (errMsg != "") {
     alert(errMsg);
     return false;
    }

    return true;
}

Email Pattern
//
var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
//

Example of Validation













The Form
   

Personal Information


Thursday, May 9, 2013

Use SyntaxHighlighter to make code beautiful

Reading code on Blogger is boring, and it needs to change.

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. You can find more information at SyntaxHighlighter.

To use blogger with SyntaxHighlighter, you need to -

1. Add below code to your template

 







2. In your blog, add html like -

function foo(){
}

Good Web Site Template

I am thinking about creating a website, and I don't want to start from scratch. Luckily, there is a bunch of templates that I can work on. 

Free Web Site Templates - FREE! It looks nice and pretty simple. The templates would be a good start if you don't need so many functions but just a website to show features of whatever you want.

Good Layers - More gorgeous and more functions developed. It costs you $45 ~ $50 to get one regular license.