Navigetion

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Monday, March 18, 2013

Auto complete using jQuery & Ajax

The Idea

You want to ask the user to enter a name in the input text field, so that the moment the user types the first character of a name, a suggestion box will appear that displays all the names beginning with the character typed. You also want the names displayed in the suggestion box to have a hovering effect – so that they become highlighted on moving the mouse pointer over them – and the clicked name to be inserted in the input text field.

Implementation

Let’s create an HTML file that displays a label: ‘Enter userid’ and an input text field. Below the input text field, we create two empty div elements that are assigned the class names: listbox and nameslist respectively. The HTML file may appear as shown below:

Enter user id

The div element of class listbox will be used for displaying a box and the div element nameslist will be used for displaying the names with hovering effect. We define the style rules to be applied to the two div elements in the style sheet file: style.css as shown here:

.listbox {
    position: relative;
    left: 10px;
    margin: 10px;
    width: 200px;
    background-color: #000;
    color: #fff;
    border: 2px solid #000;
}
.nameslist {
    margin: 0px;
    padding: 0px;
    list-style:none;
}
.hover {
    background-color: cyan;
    color: blue;
}

The jQuery code to now make our suggestion box appear when the user types the first character in the input text field, and to make the clicked name (in the suggestion box) to appear in the input text field automatically, is as shown here:

$(document).ready(function() {
    $('.listbox').hide();
    $('.userid').keyup(function () {
        var uid = $('.userid').val();
        var data='userid='+uid;

        $.ajax({
        type:"POST",
        url:"autocomplete.php",
        data:data,
        success:function(html) {
            $('.listbox').show();
            $('.nameslist').html(html);
            $('li').hover(function(){
                $(this).addClass('hover');
            },function(){
                $(this).removeClass('hover');
            });
            $('li').click(function(){
                $('.userid').val($(this).text());
                $('.listbox').hide();
            });
      }
    });
    return false;
  });
});

The script file autocomplete.php, on the server, is designed to send the list of names as response, and it should look like this:

    echo '
  • Jackub
  • '; echo '
  • Jenny
  • '; echo '
  • Jill
  • '; echo '
  • John
  • ';

    Check out your site now. Try typing a name begins with 'J'.
    Booya! If everything's goes well I believe you will get a pop-up with a list of name begins with 'j'.

    Though this is not the best way of generating the autocomplete menu and obviously we will generate the autocomplete menu using data from the database, but I believe you get the idea. I will make another post where I'm going to show how can we can grab the information(data) from the database and fill the autocomplete list with it. Knock me out if you have any question. Till then bye bye.

    Validating an Email Address usning jQuery & Ajax

    The Idea

    You want the user to enter his email address and you want to use a server-side script to confirm that it is a valid email address. This means that it must consist of alphanumericals, no symbols other than - and _ , plus it must contain both symbols . and @. If the email address is invalid, an error message should be displayed to the user.

    Implementation

    Let’s make an HTML file that displays a label: ‘Enter email address’ and an input text field and a submit button. The HTML file may appear as shown below:

    Enter email address

    We can see in above HTML file that the input text field is assigned the class name emailadd for the purpose of accessing it via jQuery code. Following the input text field, is an empty span element of class error. The text to this span element will be assigned from the server generated response, if the user enters an invalid email address.

    In order to specify width to the label, input text field and color to the error message, we will make use of the style rules written in the style sheet file from the solution we used in 8-3. The jQuery code to invoke the server side script: validatemail.php for validating the email address entered by the user is as shown below:

    $(document).ready(function() {
        $('.error').hide();
        $('#submit').click(function () {
            var em = $('.emailadd').val();
            var data='emailadd='+em;
            $.ajax({
                type:"POST",
                url:"validatemail.php",
                data:data,
                success:function(html) {
                    $('.error').show();
                    $('.error').text(html);
                }
            });
            return false;
        });
    });
    

    The script file validatemail.php, on the server, is designed to check whether the email address of the user is valid or not:

    
    

    SOME SAMPLE I/O AND RESULT

    InputResult/Output
    john-123@yahooNot accepted/Invalid email address
    john-123@yahoo.comAccepted

    Validating a User Name Using Ajax

    The Idea

    You want to ask the user to enter a name and you want to use a server-side script to confirm that the field is not left blank. If the user does not enter anything in the name field, then he should get an error message.

    Implementation

    Let’s start by creating an HTML file that displays a label: ‘Enter your Name’ and an input text field and a submit button. The HTML file may appear as shown below:

     
      
    Enter your Name

    You can see here that the input text field is assigned class name uname for the purpose of accessing it via jQuery code. Following the input text field is an empty span element of class error. The text to this span element will be assigned from the server generated response – if the user leaves the input text field blank.

    In order to specify a width to the input text field label, and a color to the error message, we need to write some style rules in the style sheet file:

    .label {float: left; width: 120px; }
    .uname {width: 200px; }
    .error { color: red; padding-left: 10px; }
    #submit { margin-left: 125px; margin-top: 10px;}
    

    The jQuery code to invoke the server side script is below, which passes to validateuser.php. the name entered by the user as a parameter, and displays an error message if the name is left blank by the user:

    $(document).ready(function() {
        $('.error').hide();
            $('#submit').click(function () {
                var name = $('.uname').val();
                var data='uname='+name;
                $.ajax({
                    type:"POST",
                    url:"validateuser.php",
                    data:data,
                    success:function(html) {
                        $('.error').show();
                        $('.error').text(html);
                    }
                });
            return false;
         });
    });
    

    The script file validateuser.php itself, is on the server, and is meant for checking whether the name of the user is not left blank. This code looks like this:

    
    

    Validating user name using a regular expression

    In the above solution, the user could enter anything when they were meant to be entering their user name – including symbols. So let’s improve the server side script so we will only accept names that consist of alphanumerical and underscore only. The script file validateuser.php can be modified as shown here to achieve this for us:

    
    

    SOME SAMPLE I/O AND RESULT

    InputResult/Output
    blankNot accepted/This field cannot be blank
    JohnAccepted
    John-123Not accepted/Invalid User Name
    John_123Accepted

    Sunday, August 5, 2012

    Authentication With AJAX and PHP

    THE IDEA

    You want to ask the user to enter a name and password in a login form. If the name and password entered by the user matches with the contents in the server side script, your user should get a welcome message, otherwise a message should declare that they are an ‘Unauthorized user’.

    Implementation

    Let’s create an HTML file that displays two labels: ‘Enter your Name’ and ‘Enter your Password’ and two input text fields and a submit button and an empty div element. The HTML file should appear like this (place following code inside your body tag):



    You can see that the HTML file contains the two input text fields that are assigned class names uname and passwd for the purpose of accessing them via jQuery code. Below the form is an empty div element of id message which we will be using for displaying the response generated by the server side script.

    AJAX and jQuery code:

    $(document).ready(function() {
     $('#submit').click(function () {
      var name = $('.uname').val();
      var pwd = $('.passwd').val();
      var data='uname='+name+'&password='+pwd;
      $.ajax({
       type:"POST",
       url:"logincheck.php",
       data:data,
       success:function(html) {
        $("#message").html(html);
       }
      });
      return false;
     });
    });
    

    The script file logincheck.php on the server validates the name and password entered by the user, and looks like this:

    logincheck.php

    $name = trim($_POST['uname']);
    $pswd = trim($_POST['password']);
    if(($name=="guest") && ($pswd=="jquery"))
      echo "Welcome ". $name;
    else
      echo "Sorry you are not authorized";
    

    And we are ready to go! Check your working AJAX Authentication application. Too sleepy to write got to go, knock me if you are stuck anywhere, bye bye :)...

    Saturday, August 4, 2012

    Displaying Welcome Message With AJAX, jQuery and PHP

    Idea

    You have a label, an input text field, and a submit button on a form, and you want a welcome message be displayed to the user when they select the submit button – once they have entered their name in the input text field.

    Implementation

    First of all, let’s create the HTML file that contains a label element, an input text field, a submit button, and an empty div element. The HTML file should look like this:

    
      

    You can see that the HTML file contains a label, an input text field, and a submit button nested in a form. The input text field is given the class name uname for the purpose of accessing it via our jQuery code that we’re about to write. Below the form is an empty div element of id message which we will use for displaying the welcome message to the user.

    Before moving forward needless to mention that as I'm going use jQuery functionality, you have import jQuery inside you head tag. You can download the latest release from here. If you are not familiar with jQuery(Are you kidding me :@) visit here to find out how to import jQuery to a site

    The jQuery and AJAX code for our solution looks like this

    $(document).ready(function(){
      $('#errorMsg').hide();
    
      $('#submit').click(function(){
       var name = $('.uname').val();
       //Checking if the input field is empty
       if( name != ''){
        var data = 'uname=' + name;
    
        //Making the Ajax call
        $.ajax({
         type: "POST",
         url: "welcome.php", //url of you php file.
         data: data,
         success: function(html){
          $('#form').hide();
          $('#errorMsg').hide();
          $('#message').html(html);
         }
        });
       } else{//if the name field is empty showing th erroe message
        $('#errorMsg').show('fast');    
       }
       return false;
      });
     });
    

    The script file welcome.php on the server is as follows

    welcome.php

    $name = $_POST['uname'];
    echo "Welcome ". $name;
    

    Don't forget to place this code in between a php tag
    Finally check out your functional AJAX page

    Now we can simply make this job done by making a POST Request of jQuery.

    Making POST requests

    For making POST requests to the server, we make use of the $.post() method, which you’ll use most generally when you want to make some modification in the information stored on the server. It fetches the data onto the server using POST HTTP request. It executes the script whose URL is specified along with the parameters passed (if any). This function also allows a single callback function to be specified that will be executed when the request is complete. Here’s the method and parameters:

    $.post(url, parameters, callback)

    • url is the server-side script to which we want to send request (via the POST method)
    • parameters is key/value pair that we want to be passed to the server-side script for processing
    • callback is the function that is invoked on completion of the request. It contains two parameters, the first is the response from the server side script and the second parameter is the status of execution
    The previous JavaScript file can therefore be modified to use the $.post() method as follows:

      $(document).ready(function() {
        $('#submit').click(function () {
          var name = $('.uname').val();
          var data = 'uname=' + name;
          $.post(
            "welcome.php",
            data,
            function (html) {
              $('#message').html(html);
            }
          );
          return false;
        });
     });
    

    You can see that the $.post() method invokes the welcome.php file on the server and passes uname=name to it as a parameter (where name stores the name entered by the user) and the callback function displays the response (from the server) by assigning it to the div element of id message.

    Finally, please do remember that the server side script welcome.php must access the data from the $_POST array and not from the $_GET array beacuse the request sent is via the POST method:

    And yes of course you can use the $.get() method in this same way but in that case you must access the data from the $_GET[] array. $.get(url, parameters, callback)

    welcome.php for $.get() request

    $name = $_GET['uname'];
    echo "Welcome ". $name;
    

    Thanks for your precious time on my content, I will appreciate you feedback. Don't burn you head if you have anything on it right now, just through it to me. xD

    Monday, July 30, 2012

    Using AJAX as Navigational Tool [ Basic Ajax Example ]

    Following example shows a generic web page that loads in content via Ajax to display different information based on the link that has been clicked.
      Before you start, first you should go through these two content to understand how to use Ajax to create a XMLHttpRequest object and how to send a request to the server.
    1 - Creating AJAX XMLHttpRequest Object
    2 - Sending a Request to the Server

    The home page or the base page where we will show our sub-pages using the magic of AJAX:


    Place it inside your 'head' tag

    
    Sample Ajax Site
    
    
    

    Place inside the body tag:

    P.S.: Please note that you have to call the function makerequest() once when the page is loading -

    It's My Ajax Page

    Home | Page 2 | Page 3 | Page 4

    Make other sub-pages in the same folder like following -


    content1.html

    
    

    Page 1

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minimveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


    content2.html

    
    

    Page 2

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minimveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


    content3.html

    
    

    Page 3

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minimveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


    content4.html

    
    

    Page 4

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minimveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Note: If you are working on you local machine, you have install and enable your local apache server, and you should run the page using localhost. There are so many server application pack out there, most popular for windows - XAMPP, WAMP, for mac MAMP. Use whichever you comfort with.
    Check out the demo from here

    As you can see, by making use of Ajax, you can create a fully functional, Ajax navigation–driven site in a manner of minutes. You include the JavaScript required to process the links into <script> tags in the head, and can then make use of the makerequest() function at any time to send a server-side request to the web server without refreshing the page. You can call the makerequest() function on any event (you are using onclick() here) to load content into the respective object that is passed to the function.

    Sunday, July 29, 2012

    AJAX TUTORIAL : Sending a Request to the Server

    First of all, you should already know how to create XMLHttpRequest object. If you already know how to create it skip this. To make a new XMLHttpRequest object please follow my this blog content - Creating XMLHttpRequest object

    Now that you have your shiny, new XMLHttpRequest object ready for use, the natural next step is to use it to submit a request to the server. This can be done in a number of ways, but the key aspect to remember is that you must validate for a proper response, and you must decide whether to use the GET or POST method to do so. It should be noted that if you are using Ajax to retrieve information from the server, the GET method is likely the way to go. If you are sending information to the server, POST is the best way to handle this. I’ll go into more depth with this later in the book, but for now, note that GET does not serve very well to send information due to its inherent size limitations.
      In order to make a request to the server, you need to confirm a few basic functionality based questions. First off, you need to decide what page (or script) you want to connect to, and then what area to load the page or script into. Consider the following function, which receives as arguments the page (or script) that you want to load and the div (or other object) that you want to load the content into.

    function makerequest(serverPage, objID) {
    
      var obj = document.getElementById(objID);
      xmlhttp.open("GET", serverPage);
    
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          obj.innerHTML = xmlhttp.responseText;
        }
      }
      xmlhttp.send(null);
    }
    

    Basically, the code here is taking in the HTML element ID and server page. It then attempts to open a connection to the server page using the open() method of the XMLHttpRequest object. If the readyState property returns a 4 (complete) code and the status property returns a 200 (OK) code, then you can load the response from the requested page (or script) into the innerHTML element of the passed-in object after you send the request.
      Basically, what is accomplished here is a means to create a new XMLHttpRequest object and then use it to fire a script or page and load it into the appropriate element on the page. Now you can begin thinking of new and exciting ways to use this extremely simple concept.

    Creating AJAX Crossbrowser XMLHttpRequest Object Instance

    Although at the time of this writing, Microsoft’s Internet Explorer continues to dominate the browser market, competitors such as Firefox have been making significant headway. Therefore, it is as important as ever to make sure your Ajax applications are crossbrowser compatible. One of the most important aspects of the Ajax functionality is that it can be deployed across browsers rather seamlessly, with only a small amount of work required to make it function across most browsers (the exception being rather old versions of the current browsers). Consider the following code snippet, which instantiates an instance of the XMLHttpRequest object, and works within any browser that supports XMLHttpRequest.

      
    //Create a boolean variable to check for a 
    //valid Internet Explorer instance.
     var xmlhttp = false;
     if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
     }
     else
     {// code for IE6, IE5
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }  
     

    Click below button to check your browser.

    The XMLHttpRequest Object

    Ajax is really just a concept used to describe the interaction of the client-side XMLHttpRequest object with server-based scripts. In order to make a request to the server through Ajax, an object must be created that can be used for different forms of functionality. It should be noted that the XMLHttpRequest object is both instantiated and handled a tad differently across the browser gamut. Of particular note is that Microsoft Internet Explorer creates the object as an ActiveX control, whereas browsers such as Firefox and Safari use a basic JavaScript object. This is rather crucial in running cross-browser code as it is imperative to be able to run Ajax in any type of browser configuration.

    XMLHttpRequest Methods

    Once an instance of the XMLHttpRequest object has been created, there are a number of methods available to the user. These methods are expanded upon in further detail in Table below. Depending on how you want to use the object, different methods may become more important than others.

    Table: XMLHttpRequest Object Methods

    Method Description
    abort() Cancels the current request
    getAllResponseHeaders() Returns all HTTP headers as a String type variable
    getResponseHeader() Returns the value of the HTTP header specified in the method
    open() Specifies the different attributes necessary to make a connection to the server; allows you to make selections such as GET or POST (more on that later), whether to connect asynchronously, and which URL to connect to
    setRequestHeader() Adds a label/value pair to the header when sent
    500 Internal Server Error This code will be returned if the server that is being contacted has a problem.
    send() Sends the current request

    XMLHttpRequest Properties

    Of course, any object has a complete set of properties that can be used and manipulated in order for it work to its fullest. A complete list of the XMLHttpRequest object properties is presented in Table below. It is important to take note of these properties you will be making use of them as you move into the more advanced functionality of the object.

    Table: XMLHttpRequest Object Properties

    Property Description
    onreadystatechange Cancels the current request
    readyState Contains the current state of the object (0: uninitialized, 1: loading, 2: loaded, 3: interactive, 4: complete)
    responseText Returns the response in string format
    responseXML Returns the response in proper XML format
    status Returns the status of the request in numerical format (regular page errors are returned, such as the number 404, which refers to a not found error)
    statusText Returns the status of the request, but in string format (e.g., a 404 error would return the string Not Found)

    AJAX HTTP Request and Response

    In order to understand exactly how Ajax concepts are put together, it is important to know how a web site processes a request and receives a response from a web server. The current standard that browsers use to acquire information from a web server is the HTTP (HyperText Transfer Protocol) method (currently at version HTTP/1.1). This is the means a web browser uses to send out a request from a web site and then receive a response from the web server that is currently in charge of returning the response.
    HTTP requests work somewhat like e-mail. That is to say that when a request is sent, certain headers are passed along that allow the web server to know exactly what it is to be serving and how to handle the request. While most headers are optional, there is one header that is absolutely required (provided you want more than just the default page on the server): the host header. This header is crucial in that it lets the server know what to serve up.
    Once a request has been received, the server then decides what response to return. There are many different response codes. Table below has a listing of some of the most common ones.

    Table: Common HTTP Response Codes

    Code Description
    200 OK This response code is returned if the document or file in question is found and served correctly.
    304 Not Modified This response code is returned if a browser has indicated that it has a local, cached copy, and the server’s copy has not changed from this cached copy.
    401 Unauthorized This response code is generated if the request in question requires authorization to access the requested document.
    403 Forbidden This response code is returned if the requested document does not have proper permissions to be accessed by the requestor.
    404 Not Found This response code is sent back if the file that is attempting to be accessed could not be found (e.g., if it doesn’t exist).
    500 Internal Server Error This code will be returned if the server that is being contacted has a problem.
    503 Service Unavailable This response code is generated if the server is too overwhelmed to handle the request.

    It should be noted that there are various forms of request methods available. A few of them, like GET and POST, will probably sound quite familiar. Table below lists the available request methods (although generally only the GET and POST methods are used).

    Table: HTTP Request Methods

    Method Description
    GET The most common means of sending a request; simply requests a specific resource from the server
    HEAD Similar to a GET request, except that the response will come back without the response body; useful for retrieving headers
    POST Allows a request to send along user-submitted data (ideal for web-based forms)
    PUT Transfers a version of the file request in question
    DELETE Sends a request to remove the specified document
    TRACE Sends back a copy of the request in order to monitor its progress
    OPTIONS Returns a full list of available methods; useful for checking on what methods a server supports
    CONNECT A proxy-based request used for SSL tunneling

    Now that you have a basic understanding of how a request is sent from a browser to a server and then has a response sent back, it will be simpler to understand how the XMLHttpRequest object works. It is actually quite similar, but operates in the background without the prerequisite page refresh.

    REQUIREMENTS FOR AJAX

    Before starting I would like to mention few words about the post, this content was collected form the book named "Beginning Ajax with PHP - From Novice to Professional". Basically according to the blog title, this is my notebook. I am not a professional developer, I am student and I am just sharing what I am learning with my fellow learners. If somehow this content is a cause of violation please ping, I will be glad to know if there is any problem.

    AJAX REQUIREMENT

    Since Ajax is based upon JavaScript technology, it goes without saying that JavaScript must be enabled in the user’s browser in order for it to work. That being said, most people do allow their browsers to use JavaScript, and it is not really that much of a security issue to have it in place. It must be noted, however, that the user does have the ability to effectively “disable” Ajax, so it is important to make sure, when programming an Ajax application, that other means are available to handle maneuvering through the web site; or alternatively, that the user of the web site is kept properly informed of what is necessary to operate the application.
      Ajax is a fairly widely supported concept across browsers, and can be invoked on Firefox (all available versions), Internet Explorer (4.0 and higher), Apple Safari (1.2 and higher), Konqueror, Netscape (7.1 and higher), and Opera (7.6 and higher). Therefore, most browsers across the widely used gamut have a means for handling Ajax and its respective technologies.
      At this point, the only real requirement for making use of Ajax in an efficient and productive manner is the creativity of going against what the standard has been telling us for years, and creating something truly revolutionary and functional.