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.

      Thursday, October 7, 2010

      Search and replace of exact matching string in PHP

      If you have to make and exact search, use preg_replace function with simple regular expression pattern. This function is used to search and replace a string according to the pattern provided.
      mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
      mixed = any type of data, from  string to array.
      array to array replace, string to string replace.
      If your pattern doesn't contain regular expression, and you are going to search and replace string, please use str_replace function instead.
      $replacement is the new string that will substitute the string or array following the pattern.
      $subject is the array or string in which search and replace operation performs.

      To make exact match, you have to use \b in both sides of the pattern.
      For example, 
      $pattern="/\bpatternstring\b/"; or
      $pattern="/\b[0-9a-zA-Z]+\b/";
      If you have to escape any special characters, then use \ (backslash) before that character.
      $pattern="/\bxyz\[\]pqrs\b/";
      If you have to make the search irrespective of case, need to use i , if in your subject includes utf-8 characters, use u,in the pattern.
       $pattern="/\bxyz\[\]pqrs\b/iu";

      Sunday, October 3, 2010

      Best way to easily import heavy amount of data in MySQL database?

      Dear friends,

      We usually use phpmyadmin tool to do all types of database related operations. But, sometimes when we have large sql dump which PhpMyadmin failed to execute due to upload size and execution time limit of PHP script.
      Then either you have to use MySQL GUI tools like SQLyog, Navicat or MySQL query browser or use MySQL command line.
      Best way to export the DB is below:

      E:\MySQL\MySQL Server 5.1\bin>mysqldump -u jroot -pjoomla1 -h hostname dbname > e:\backupfile.sql

      If we want to export only table structure, execute below command:
      mysqldump -ujroot -pjoomla1 -hlocalhsot --no-data prodtest  > e:\MySqlBkups\19112013jprod.sql
      If we want to export only data of tables in a database, execute below command:
      mysqldump -ujroot -pjoomla1 -hlocalhost --no-create-info prodtest  > e:\MySqlBkups\19112013jprod_data.sql
      If we want to ignore a table during export a database, execute below command:
      mysqldump -ujroot -pjoomla1 -hlocalhost jprodtest --ignore-table=jprod.sessions > e:\MySqlBkups\19112013jprod_data.sql

      There are 3 ways to import the data using command line.
      1. The LOAD DATA statement
      2. The source Command
      3. The mysql command
      Second way, source command is the best way among these. Below is the way to import :
      • First, you should logged-in to the MySQL and put the sql file wherever you want. To login on mysql command prompt, you have to go to the inner directory of mysql. For example,                                    c:>cd wamp/bin/mysql/mysql5.0.45/bin
      • A) c:/wamp/bin/mysql/mysql5.0.45/bin>mysql -u root -p***** -hipaddressofhost
        • mysql> source <path>filename.sql;
      • B) C:\wamp\bin\mysql\mysql5.5.24\bin>mysql -u <username> -p<password>  -D<dbname> <c:\filetoimport.sql
      Note:  there should not be any space between -p and password. It will be same for -h and hostname. Space will be between -u and username.
      These are 3 simple steps to execute a sql dump file. It will take very less time to execute heavy queries.




      Feel free to comment on my post, if you find any difficulty to implement.

      How to include an external file in Joomla?

      Dear friends,

      In some cases, you need to add an external file beside joomla file system in a module and component. In this case, your external file can't use the joomla libraries easily. Following is the way to use the external file.
      Add following 10 lines of code on top of your external file.
      define( '_JEXEC', 1 );
      define('JPATH_BASE', dirname(__FILE__));
      define( 'DS', DIRECTORY_SEPARATOR );
      require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
      require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
      $mainframe =& JFactory::getApplication('site');
      $mainframe->initialise();
      /* If you need to use database object, add following line too */
      $db=JFactory::getDBO(); // use this $db object for database related operation



       Now, use this file as normal joomla file. You can include the joomla libraries  files as per the requirement also.

      Feel free to provide your comment.

      Sunday, September 19, 2010

      Welcome to Web development stuff blogs

      Welcome readers. Here, you will get the solution of all the typical problems which you face regularly on your web application development tasks. I update this blog on regular basis. It is dedicated to LAMP/WAMP developer community from all over the world. My blog will include problems related with HTML, CSS, Javascript, JQuery, PHP, MySQL, Apache, Ubuntu, Joomla and wordpress.


      I follow this formula:
      Web designing + Programming = Web development

      Feel free to comment on my post and and ask question from LAMP/WAMP technology.

      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...