28 November 2009

How to make suggetion box using ajax in php from database onchange event

Hell Friends
Here is the example to get data from database using ajax in php (autocomplete)

This is the front page viewable to the user. Here is the input box that get input by the user and showData function take the request and send it to the getdata.php file via ajax and send response to the user.

index.php


<html>
<head>
<title>autocomplete | Home</title>
<script type="text/javascript">
  var xmlhttp;

  function showData(str) {
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null) {
      alert ("Browser does not support HTTP Request");
      return;
    }
    var url="getdata.php";
    url=url+"?q="+str;
    url=url+"&sid="+Math.random();
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(nodata);
  }

  function stateChanged() {
    if (xmlhttp.readyState == 4) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    } else {
      document.getElementById("txtHint").innerHTML="No Data available";
    } 
  }

  function GetXmlHttpObject() {
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      return new XMLHttpRequest();
    }
    if (window.ActiveXObject) {
      // code for IE6, IE5
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
  }
</script>
</head>

<body>
 <div align="center" style="padding-top:10%; padding-left:25%; width:400px;">
   <table>
     <tr>
       <form>
         <td><span style="font-size:14px; font-family:Verdana, Arial, Helvetica, sans-serif;">Type any letter here</span></td>
         <td><input type="text" name="txtblog" id="txtblog" value="" onchange="showData(this.value)"/></td>
       </form>
     </tr>
     <tr>
     <td> </td>
       <td>
         <div align="right" style="overflow:scroll; max-height:200px;" id="txtHint"> </div>
       </td>
     </tr>
   </table>
  </div>
</body>
</html>

getdata.php


<?php
mysql_connect('HOST_NAME','USERNAME','PASSWORD');
mysql_select_db('DB_NAME');

$q = $_GET["q"];
$sql = "SELECT * FROM TABLE_NAME WHERE SEARCHING_COULMN_NAME like '%".$q."%'";
$result = mysql_query($sql);
echo '<table>';

while($row = mysql_fetch_array($result)) {
  echo '<tr>';
  echo '<td>' . $row['SEARCHING_COULMN_NAME'] . '</a></td>';
  echo '</tr>';
}
echo '</table>';
?>

26 November 2009

Check username availability from database in php using jQuery

Hell Friends
here is an example to Check username availability from database in php using jQuery. This will be done with three steps.
  1. First create a file "index.php" or whatever you want.
  2. Create a "user_availability.php".
  3. Create database named "test" and table named "login".

What is jquery?

JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

index.php(This is the file from where you will input username)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Username availability Checking using jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="jquery-1.3.2.min.js" type="text/javascript" language="javascript"></script>
<script language="javascript">

$(document).ready(function()
{
    $("#username").blur(function()
    {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
        {
          if(data=='no') //if username not avaiable
          {
              $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            {
              //add message and change the class of the box and start fading
              $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
            });       
          }
          else
          {
              $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
            {
              //add message and change the class of the box and start fading
              $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);   
            });
          }
               
        });

    });
});
</script>
<style type="text/css">
body {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:11px;
}
.top {
margin-bottom: 15px;
}
.messagebox{
    position:absolute;
    width:100px;
    margin-left:30px;
    border:1px solid #c93;
    background:#ffc;
    padding:3px;
}
.messageboxok{
    position:absolute;
    width:auto;
    margin-left:30px;
    border:1px solid #349534;
    background:#C9FFCA;
    padding:3px;
    font-weight:bold;
    color:#008000;
   
}
.messageboxerror{
    position:absolute;
    width:auto;
    margin-left:30px;
    border:1px solid #CC0000;
    background:#F7CBCA;
    padding:3px;
    font-weight:bold;
    color:#CC0000;
}

</style>
</head>
<body>


<br>
<br>
<div align="center">
<div class="top" >
  Please move the focus out of the box to check the availability of username
</div>
<div >
   User Name : <input name="username" type="text" id="username" value="" maxlength="15" />
   <span id="msgbox" style="display:none"></span>
</div>

</div>
</body>
</html>

user_availability.php


if(isset($_POST['username'])) {
   $username = mysql_real_escape_string($_POST['username']);
   if(!empty($username)) {
     $username_query = mysql_query("SELECT COUNT(`id`) FROM `login` WHERE `username` = '$username'");
     $username_result = mysql_result($username_query,0);
     if($username_result == 0) {
       echo 'yes';
     } else ($username_result == 1) {
       echo 'no';
     }
   }
  }

Database script:


CREATE TABLE `login` (
  `id` bigint(20) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phoneno` bigint(15) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;


INSERT INTO `login` (`id`, `username`, `password`, `email`, `phoneno`) VALUES
(1, 'ankit', '123', 'ankit@gmail.com', 9953471700);

24 November 2009

Ajax login Form using Moo Tool

Hello Friends
I have created an Ajax login application with Moo Tool.
What is Moo Tool?
MooTools is a compactmodularObject-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerfulflexible, and cross-browser code with its elegant, well documented, and coherent API.

Some Screen Shots are here of it.
This is the main login page.
ajax login form page

This is the page after logged in by user.
ajax welcome page
If you want download it, please
Click here

21 November 2009

select all checkboxes in single check

<html>
<title> select all checkboxes in single check
</title> 
<head>
 <script language=javascript>
checked=false;
function checkedAll (form1) {
    var aa= document.getElementById('form1');
     if (checked == false)
          {
           checked = true
          }
        else
          {
          checked = false
          }
    for (var i =0; i < aa.elements.length; i++)
    {
     aa.elements[i].checked = checked;
    }
      }
</script
</head>
 <body>
<form name="form1" method="post" id="form1">
<table>
    <tr>
       <td><input type='checkbox' name='checkall' onclick='checkedAll(form1);'> </td>
    </tr>
    <tr>
    <td> </td>
    </tr>
    <tr>
    <td>Checkbox1: <input type='checkbox' name='chk'value=""> </td>
    </tr>
    <tr>
    <td>Checkbox 2: <input type='checkbox' name='chk'value=""> </td>
    </tr>
</table>
</form>
</body>
</html>

20 November 2009

How to do autorefresh using javascript

  1. If you want to refresh your page automatically after loading the page
    <html>
    <head>
    <script type="text/JavaScript">
    function timedRefresh(timeoutPeriod) {
    setTimeout("location.reload(true);",timeoutPeriod);
    }


    </script>
    </head>
    <body onload="JavaScript:timedRefresh(5000);">

    This page will refresh every 5 seconds. Here we are using the "onload" event to call our function. We are passing in the value '5000', which equals 5 seconds.
    </body>
    </html>
  2. If you want to refresh a page "on click", type the following code as:-

    <a href="javascript:location.reload(true)">Refresh this page</a>


18 November 2009

how to use explode function in php

Here is the example to use explode function on an array fetched from database values separated by comma ( , ) and count duplicate values also.
  1. First create database " your database" and a table named "blog".
  2. Enter some data a:-
  3. For first row- insert following data---   Ankit, Om
  4. For second row- insert following data---   Ankit, Ajeet, Santosh.
  5. After that create a php page and paste following coding and change username, password and database name.

<table cellpadding="0" cellspacing="0" class="backcolor" style="border: 1px solid rgb(204, 204, 204);">
<?php
mysql_connect('localhost','Username','Password');
mysql_select_db('database_name');
$sql = "select tag from blog";
$result = mysql_query($sql)or die('Error in get blog detail'.mysql_error());
$toTagArray = array();
$i=0;
while($tag = mysql_fetch_row($result)){
  $TagArray = explode(",", $tag[0]);
  $toTagArray = array_merge($toTagArray,$TagArray);
  $i += 1;
}
$new_array = array_count_values($toTagArray);
ksort($new_array);
while (list ($key, $val) = each ($new_array)) {
?>
<tr>
  <td style="font-size: 12px; padding-left: 20px;">
    <ul>
      <li><?php echo "$key  ($val) <br>";?></li>
    </ul>
  </td>
</tr>
<?php }?>               
</table>

The output will be like as:-
Ajeet (1)
Ankit (2)
Om (1)
Santosh (1)

14 November 2009

How to ban an IP address or site name using .htaccess

Ban using IP address. These are sample IP addresses...

42.12.5.34
193.110.145.185 
Code For .htaccess:

<Limit GET POST>
order allow,deny
 deny from 42.12.5.34
 deny from 193.110.145.185
 allow from all
</Limit>
To ban using site name. Do NOT include the "http://www." portion!
These are sample site names:...

domain.com
abc.com

## SITE REFERRER BANNING
RewriteEngine on
# Options +FollowSymlinks


RewriteCond %{HTTP_REFERER} domain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} abc\.com [NC]
RewriteRule .* - [F]


13 November 2009

How to enable right click on site that is disabled

In Fierfox

  1. Got to the menu bar, click on Tool menu and go to the "Option" and click here.
  2. Click on "content".
  3. Click on "advanced" button.
  4. Uncheck the "Disable or replace context menus".
  5. Refresh the page , right click will work.

In Internet Explorer  

  1. Go to "Internet Options" 
  2.  Click the "Security" tab
  3. Click "Custom Level" 
  4. Scroll down to the "Scripting" section 
  5. Set "Active Scripting" to "disable" 
  6. Click "Ok" a couple of times.

How to disable the right click


<html> 
<head>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
</head>
<body></body>
</html> 


12 November 2009

How to add Your Blogspot Blog Sitemap to Google Webmaster Tools

  1.  First open the Google Webmaster Tools website at google.com/webmasters and click "Add a Site" button to submit
  2. You can either type the web address (URL) of your blogspot.com blog or even a self-hosted blog where you are using the Blogger platform with your personal domain.
  3. Google will ask you to verify that you are the owner of this blog. Just copy-paste the given meta code and then paste this information into the template of your blog.
  4. You must switch to the "HTML" version of your blog template and paste the code just between the head .........tag
  5.  Go back to Google Webmaster Tools and click on "Sitemaps" from the right sidebar.
  6. Type the url atom.xml?redirect=false otherwise you can write atom.xml it will also work.Once the clock status icon changes to a green tick, your Blogger sitemap has been successfully submitted to Google for indexing.
  7. If you are using Feed Burner for your Blogger RSS feed, then redirect=false paramater will force to Google to download your blogger feed.

09 November 2009

StringList class and use of it

This class can be used to manage lists of strings. It can take a list of strings separated by line breaks and extracts key value pairs separated by the = character.The class can return the list of strings as an array, add more strings to the list, and save or load the list from a file.

stringlist_class.php


class StringList{
  private $Values=array();
  private $Text;
  private $Lines=array();
  /**
  * It's constructor func
  *
  * @param mixed $string String you want parse.
  * @return StringList
  */
  public function StringList($string){

    $this->Text=$string;
    $this->Lines=explode("\n",$string);
    $Count=count($this->Lines);

    Foreach ($this->Lines As $LineText){
      $EsitPos=strpos($LineText,'=');
      $this->Values[substr($LineText,0,$EsitPos)]=substr($LineText,$EsitPos+1,strlen($LineText));
    }

    return $this;
  }
  /**
  * Return The Text Or Set Text (ReCreate Object).
  *
  * @param mixed $SetTex it will change if it assigned
  * @return StringList
  */
  public function Text($SetTex=False){
    if($SetTex){
      return $this->StringList($SetTex);
    } else {
      return $this->Text;
    }
  }
  /**
  * It can return A Line or All Lines Or Set The Lines ( ReCreate Object )
  *
  * @param mixed $LinesArray if is numeric it will return Line with this number .
  * @return StringList
  */
  public function Lines($LinesArray=false){
    if(is_array($LinesArray)){
      return $this->StringList(implode("\n",$LinesArray));
    } elseif(is_numeric($LinesArray)) {
      return $this->Lines[$LinesArray];
    }else {
      return $this->Lines;
    }
  }
  /**
  * You Can add Line Or Lines by Array.
  * @param mixed $LineOrLines
  */
  public function Add($LineOrLines){
    if(strstr($LineOrLines,"\n")){
      $Lines=explode("\n",$LineOrLines);
    }else {
      $Lines[]=$LineOrLines;
    }

    Foreach($Lines As $Line){
      $this->Lines[]=$Line;
    }
   return $this;
  }
  /**
  * Save Text to File.
  * @param mixed $FileName Dosya Adı
  */
  public function SaveToFile($FileName='UnnamedStringlistFile'){
    if($fileOpened=@fopen($FileName,'w+')){
      fwrite($this->Text);
      fclose($fileOpened);
    }
  }
  /**
  * Read Text From File (Recreate Object)
  *
  * @param mixed $FileName
  */
  public function ReadFromFile($FileName){
    if(is_file($FileName) && is_readable($FileName)){
      $this->StringList(file_get_contents($FileName));
    }
    return $this;
  }
  /**
  * PROPERTIES
  */
  public function Values($Name=false,$SetValue=False){
    if($Name){
      if($SetValue){
        foreach($this->Values AS $valName=>$valValue){
        $Lines[]=$valName.'='.$valValue."\n";
      }
      $this->Lines($Lines);
      } else {
        return $this->Values[$Name];
      }
    } else {
      return $this->Values;
    }
  }
  public function Count(){
    return Count($this->Lines);
  }

  /**
  * This func is only for show ->Lines()->Add() etc on PHP Editores
  *
  */
  private function ForPhpEditores(){
    die('Don\'t Use This Function.!');
    $this->Text=new StringList('');
    $this->Lines=new StringList('');
  }
} 

example.php


include 'stringlist_class.php';
$str=new Stringlist("Key=Value\nKey2=Value2");

echo $str->Values('Key2'); // return Value2
$str->SaveToFile('file.txt'); //will write Key=Value\nKey2=Value2 2 lines on file.txt
$str->Count(); // return 2
$str->Text(); //Return All Text
$str->Text('new Text=asdasd'); // Set The Text
$str->Lines()->Add('newline=newValue'); // Add a New Line. 


05 November 2009

Now PHP at IBM


Now the greate news for PHP developersis that:-

  1.  IBM has created a mainframe version of PHP, that widely used for scripting-language software that lets servers create Web pages on the fly from information stored in a database.
  2. The company published the work on its AlphaWorks Web site for research projects it wants others to try out.
  3.  The software requires version 1.6 or later of the z/OS mainframe operating system. The software uses version 5.1.2 of PHP.

04 November 2009

Microsoft burrow into PHP

Open-source initiatives at Microsoft are important to the open-source community because they give developers greater exposure for their products through access to a broadly adopted platform...
But that's only part of the Web battle. Web scripting languages like PHP have been heavily influential in developing the Web, and today, PHP and its clan are largely hardwired for MySQL, not Microsoft's SQL Server.

My First Blog

Hi viewers
                This is my first blog. I am starting it to give you the updates and any type of help on latest computer technology.
So please follow me to get daily update.