Thursday, December 30, 2010

What is AJAX

AJAX stands for "Asynchronous JavaScript And XML".
It is a browser technology independent of web server software. It can directly communicate with the server using the Javascript XMLHttpRequest object. We can say that by the use of this object, JavaScript has become able to trade data directly with the server. With an HTTPRequest, a web page can make a request to, and get a response from a web server without reloading the page. The user will stay on same page and he/she will not notice that scripts request pages or send data to a server in the background. The best example which we she everyday is google suggest. Now, we can assume how much an AJAX application is useful! But, it is not useful everywhere. It has also some drawbacks too. So, it is not preferable to apply AJAX everywhere.
There are two ways that AJAX can access the server.
Synchronous :- In this way, script stops and waits for the server to send back a reply before continuing.
Asynchronous :- In this way, script allows the page to continue to be processed and will handle the reply if and when it arrived. Due to implementation of this way, processing become richer,user friendly, smoother as well as reduce the gap between desktop application and web application.
AJAX is based on following web standards:
  • JavaScript
  • XML
  • HTML
  • CSS
Different browsers uses different methods to use XMLHttpRequest object. For example, Firefox,Opera,Safari,Netscape use JavaScript built-in method - XMLHttpRequest while IE uses ActivexObject.

Properties of  XMLHttpRequest object
  1. onreadystatechange
  2. readystate
  3. responseText
  4. responseXML
  5. status
  6. statusText  
Methods of  XMLHttpRequest object
  1. open()
  2. send()
  3. abort()
  4. getAllResponseHeaders()
  5. getResponseHeaders()
  6. setRequestHeader()
Best way to use AJAX using jQuery is below:
google.load("jqueryui", "1.8.2");
var total;
total = jQuery.ajax({url: live_site+"/plugins/content/extravote/ajax.php",global: false, type: "POST",data: ({task : "getrating",cid:id,xid:xid,column_name:"rating_sum",dummy:new Date().getTime()}),
      dataType: "text",async:false,
      success: function(msg){ }
   }
).responseText;
alert(total);

    Prototype in javaScript

    Prototype is a prebuilt object  in javascript (introduced in version 1.1) which makes it possible to add one or more properties/methods in a single or all instances of an object (both types of object - prebuilt and custom).
    Case 1: Below is the example to add custom property to single instance only:
    //adding a custom property to a prebuilt object
    var myimage=new Image()
    myimage.size="26k"
    /*adding a custom property to the custom object "circle"*/
    //First, create the custom object "circle"
    function circle(){
    }
    var smallcircle=new circle()
    smallcircle.pi=3.14159
    Case 2: We have to use prototype keyword to apply a property to all instances of an object Below is an example:
    //First, create the custom object "circle"
    function circle(){
    }
    circle.prototype.pi=3.14159
    // create the object method
    function alertmessage(){
    alert(this.pi)
    }
    circle.prototype.alertpi=alertmessage

    Now, all instances of circle() now has the pi property prebuilt into them. Also, all instances of the circle object contain a alertmessage() method!

    case 3: Extending functionality to the pre-built string() object
    We can use the prototype object on any custom objects. But, it is not for prebuilt object only. Javascript allows us to "prototype" prebuilt objects that are created with the new keyword like string object, image object, Array object, date object.

    <script type="text/javascript">
    /*code for extending String object with method that writes text backwards*/

    //core custom method for writing text backwards
    function outputbackwards(){
    for (i=this.length-1;i>=0;i--)
    document.write(this.charAt(i))
    }
    //Attach custom method to string object
    String.prototype.writeback=outputbackwards
    </script>
    The above code just added a whole new functionality to the default string object- the ability to output any text backwards! Here are a few examples:
    <script type="text/javascript">
    var message1="Welcome to my site!"
    message1.writeback()
    var message2="Today is a beautiful day"
    message2.writeback()
    </script>
    Output:
    !etis ym ot emocleW
    yad lufituaeb a si yadoT
    Web Development and Design Foundations with XHTML (5th Edition)

    Real example of prototype object feature of javascript. Following is the function which is used to trim spaces.
    String.prototype.trim = function ()
    {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }

    Sunday, November 28, 2010

    How to load a php extension in LINUX/UBUNTU

    PHP has a lot of extension. It may be possible that PHP has not compiled with all extensions. If some extension is missing and it is required for our application then PHP need to enable that.
    Enable an extension in Window environment is easy. Open php.ini file and remove the ; before the module and restart the server. But, to enable an extension in LINUX, it is not so easy. Steps are below:
    1. open synaptic with admin controls...    
            sudo synaptic
    2. Search your extension which you want to load using search tool
    3. Select extension(s) from the list.
    4. Click on apply. Selected extension(s) will be installed


       

    5. Now open php.ini file (/etc/php5/apache2/php.ini) and add following line
    ;for windows environment, use .dll
    extension=newextension.dll

    ;for LINUX environment, use .so

    extension=newextension.so
    For example, to install curl,ffmpeg and json
    extension=php_curl.dll
    extension=ffmpeg.so
    extension=json.so

    6. Save the file and restart the apache by writing following line in terminal window.
    sudo /etc/init.d/apache2 restart

    The most easiest way to install an extension in ubuntu flavor is below:
    Open Applications > Accessories > terminal
    write sudo apt-get install extension1 extension2 extension3.
    For example, to install curl extension, command should be like this
    sudo apt-get install curl libcurl3 libcurl3-dev php-curl

    What is the use of enctype attribute in HTML form?

    ENCTYPE is an attribute in HTML form which is used whenever we have to upload file(s). But have we ever thought about what this attribute do? Why do we not receive any file information on server if this attribute is not used in the form?
    The default value of enctype attribute is "application/x-www-form-urlencoded". But, in case of file upload you should use "multipart/form-data".
    ENCTYPE determines how the form data is encoded. Whenever data is transmitted from one place to another, there needs to be an agreed upon means of representing that data. ENCTYPE separates the uploaded data into text and binary. Only then uploaded file information will be accessed on server side via $_FILE['filecontrolname']. Other field of form will be accessed via $_REQUEST['controlname'] or $_GET['controlname'] or $_POST['controlname'].

    Saturday, November 27, 2010

    Difference between MyISAM and InnoDB and which one is preferred?

    When we don't specify table type, a MyISAM table is created by default.
    InnoDB : It is a transaction-safe table that is managed by the InnoDB handler. As a result, data is not stored in a .MYD file, but instead is manged in the InnoDB tablespace. InnoDB tables also support full foreign key functionality in MySQL, unlike other tables. In addition, the InnoDB handler supports automatic recovery and row-level locking. InnoDB tables do not perform as well as MyISAM tables.

    MyISAM:  It is default table type in MySQL. It supports extensive indexing and are optimized for compression and sped. It also supports backward compatibility. Unlike other tables types, BLOB and TEXT columns can be indexed and null values are allowed in indexed columns. MyISAM tables are not transaction-safe, and they do not support full foreign key functionality.

    Which table type should be used when huge amount of update query has to perform?
    When need to update a table multiple times, InnoDB is preferred. Because, it do row-level locking. i.e. only one row will be lock on which updation is going on.. While MyISAM do table-level lockin i.e. whenever an update query is going to execute on a table, whole table will be locked. So, other queries which have to make operation on that table, need to wait untill the table has been unblocked. MyISAM is faster than InnoDB. So, this table type should be used in those cases where multiple queries is executing to fetch the data from the table only. For example, applications such as blog need to show the data only.

    What happened when you add a table in your MysQL database

    Whenever you add a table to a database, one or more of the following types of files are created in the database subdirectory (a directory is created which name is same as name of the database).
    1. .frm - The primary table-related file that is used to define the table's format. All table types have an associated .frm file.
    2. .MYD - The file that stores the data contained in several table types.
    3. .MYI - An index file used by several table types.
    4. .MRG - A special type of file that is used to list the name of merged tables.
    To define a table type, we must include an Engine clause at the end of  table definition, after the parentheses that enclose table elements.
    Engine = { BDB | MEMORY | ISAM | INNODB | MERGE | MYISAM }
    For example,
    CREATE TABLE AuthorBios
    {
       AthoID SMALLINT UNSIGNED NOT NULL,
       YearBBorn YEAR NOT NULL,
       CityBorn VARCHAR(40) NOT NULL DEFAULT 'Unknown'
    }Engine=INNODB;
      It is not required that for every table type (storage engine), all files will create. Below is the details about it.

      Table Type                                                                             Files used
      BDB                                                                                         .frm,.MYD,.MYI
      MEMORY                                                                               .frm
      InnoDB                                                                                     .frm
      ISAM                                                                                       .frm,.MYD,.MYI
      MERGE                                                                                    .frm,.MRG
      MyISAM                                                                                  .frm,.MYD,.MYI

      Saturday, November 20, 2010

      How to reverse a string

      Dear friend,
      Today, almost all modern languages have their own built-in methods to reverse a string. For example, PHP have strrev($stringtoreverse) while ruby has stringtoreverse.reverse utility to reverse the string. Availability of these methods prohibit us to think about the small-small logic behind these methods. Sometimes, it may be the harmful for developer community too. Following is the code in PHP to reverse a string:


      <?php

          echo str_rev('abcxyz'); //called the method

          function str_rev($stringtoreverse) //strrev is built-in method. So, str_rev is defined as custom function

          {

              $revstr=''; //initially empty string

              $len=strlen($stringtoreverse);

              for($i=$len-1;$i>=0;$i--)

              {

                  $revstr.=substr($stringtoreverse,$i,1); //concat each character returned by substr method

              }

              return $revstr;

          }  

      ?>

      Please feel free to make your valuable comment.

      Important queries based formulas to watch performance of a MySQL based application

      (1) Session Vs global status variables value select G.variable_name,G.variable_value GlobalValue,S.variable_value SessionValue from (selec...