Tuesday, September 10, 2013

Simple Search Engine Like Google using AJAX


Simple Search Engine like Google using AJAX 

This tutorial for those peoples who are looking for the sample code for a simple search engine like google. Here i am, showing my own code for a simple search engine. Here are two files one for client side file which has one text box for your query and second one is the back end code for searching data from database.

This example in HTML and JSP with AJAX support.
So you need to have the knowledge of JSP and AJAX.

search.html

<html>
<head>
<title>Search Anything</title>
<script type="text/javascript">
function GetBObject()
{
 var http;
 if(window.XMLHttpRequest)
  http=new XMLHttpRequest();
 else
  http=new ActiveXObject("Microsoft.XMLHTTP");

 return http;
}
var https=GetBObject();
function Search(obj)
{
 var URL="Search.jsp?s="+obj;
 https.open("GET",URL);
 https.onreadystatechange=handleSearch;
 https.send(null);
}
function handleSearch()
{
 if(https.status==200&&https.readyState==4)
 {
  document.getElementById("show").innerHTML=https.responseText;
 }
}
</script>
</head>
<body>

  <input type="text" style="border-radius:5px;height:50px;width:400px;margin-left:200px;margin-top:200px;font-size:40px;" onkeyup="Search(this)" placeholder="Search Anything">
  <div id="show"></div>
</body>
</html>


Search.jsp

<%@page language="java" import="java.sql.*" %>
<%
String search=request.getParameter("s");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:data");
ResultSet rst;
Statement stm=con.createStatement();
rst=stm.executeQuery("select title,url,description from searchdata where title like '"+search+"%'");
String data="<div>";
while(rst.next())
{
 data+="<table><tr><td>"+rst.getString(1)+"</td></tr><tr><td>"+rst.getString(2)+"</td></tr><tr><td>"+rst.getString(3)+"</td></tr></table>";
}
data+="</div>";
out.print(data);
%>
Saturday, July 27, 2013

JavaScript Tutorials


JavaScript:- JavaScript is an Object Based Client side scripting language which is used to apply the client side validations on web forms. It is a widely used language for web applications to apply form validations on entered data from the user. JavaScript has the power of doing anything on web browser and most of the browsers support JavaScript. It is a simple language which has the simplest syntax to use it. The all syntax of conditions, looping, switch case etc are similar to the C language and it is quite similar to the Java programming language.

Advantages of JavaScript:-

1. It is used to apply client side validations on web pages.
2. It provide the list of predefined objects which are easy to use and easy to learn.
3. JavaScript can be used to make the  web applications like calculators, games etc.
4. JavaScript is very popular for its browser support most of the browsers support JavaScript.
5. It is also used to make Asynchronous request to the server with XML, this technique is called AJAX.
6. The popular JQuery is also a JavaScript library to design the interactive web pages.
7. It can be used to design web pages dynamically.


1. Taking input from keyboard in JavaScript
2. Add two numbers with javascript




Sunday, July 21, 2013

Add two Numbers in JavaScript Inputting from KeyBoard


KeyBoard input in JavaScript:-

As like other programming languages like C, C++, Java, C# etc, JavaScript does not support direct input from console because its not working on console. JavaScript working only on web browser and the interpreter for JavaScript is browser itself.

If you want to get input from keyboard in JavaScript then JavaScript provide two options one is, input from HTML controls like TexBox and second is, prompt().

here is a tutorial for getting input by both the methods:-




Live Demo
Enter Number
Enter Number
Result

HTML Code


<tr><td>Enter Number</td><td><input id="num1" type="text" /></td></tr>
<tr><td>Enter Number</td><td><input id="num2" type="text" /></td></tr>
<tr><td>Result</td><td><input id="res" type="text" /></td></tr>
<tr><td><input onclick="sum()" type="button" value="ADD" /></td></tr>
</tbody></table>

JavaScript Code


<script type="text/javascript">
function sum()
{
var n1=parseInt(document.getElementById('num1').value);
var n2=parseInt(document.getElementById('num2').value);
document.getElementById('res').value=(n1+n2);
}
</script>
Wednesday, July 17, 2013

Animated Tool Tip in CSS3,Email Validation with JavaScript



Cool Animated Tool tip Validation of Email Address

This is a tutorial on how to create tool tip alert for any invalid entry into a textbox. Here i am telling you how to create a tool tip on onblur event of textbox.

Whenever you type any value into a textbox and its value is correct then it will not show tool tip notification but if you type wrong value and leave the textbox then it will show a tooltip for correct the value.
This is a tutorialfor checking the email address. type an email into it and leave the text box if your email is in valid format then it will not show tooltip but if it is invalid then it show you the tooltip
Type any value in above text box and check your email format is valid or invalid if valid it will not show any thing but if invalid then it will show a tooltip.

The code of above technique is as follows----

Code for creating tooltip

<div id="tooltip" style="background: #666; border-radius: 4px; color: white; display: none; height: 25px; left: 20px; position: absolute; top: 180px; width: 188px;">
<div style="font-size: 12px; margin: 4px 0 0 27px; position: absolute; z-index: 2;">
Email Format Incorrect!</div>
<div style="background: #666; height: 20px; margin-left: 15px; margin-top: 10px; transform: rotate(45deg); width: 20px;">
</div>
</div>

Code for animate the tooltip-

<style type="text/css">
#tooltip{
animation:hex infinite ease-in-out 1s;
    }
    @-moz-keyframes hex
    {
        from{margin-top:0px}
        to{margin-top:1px}
    }
</script>

code for checking email address validity--

<script type="text/javascript">
function checkEmail(obj,obj1)
    {
        obj.style.border="";
        obj1.style.display='none';
        var exp=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        if(obj.value=="")      
        {
            obj1.style.display='block';
            obj1.focus();
        }
        else if(!exp.test(obj.value))
        {
            obj.style.border='2px solid #ff3b4e';
            obj1.style.display='block';
           
        }
       
    }
</script>

Code for calling it:-

<input type="textbox" onblur="checkEmail(this,document.getElementById('tooltip'))" onfocus="document.getElementById('tooltip').style.display='none'">


What is ASP.Net, Diffrence Bw ASP and ASP.Net


ASP.Net:- The ASP.Net is a Microsoft's Technology to design and developed the complex enterprise web applications and secure Web Applications. It is a server side technology to build the dynamic web applications for internet. You can develop ASP.Net applications with several languages leik VB, C#, F# etc. This technology is popular for its simplicity and pre built controls for design a web page. The Microsoft's Visual Studio is a most popular  IDE to design and develop the web applications into ASP.Net. It is provide the drag and drop facility for controls into a web pages, with the help of visual studio you can design and customize your web pages easy and quickly. With the help of ASP.Net you can have the power of pre built controls like gridview to show the records easily and you can edit, update and delete your records in gridview instantly, you can display lacks of records without making any table with the help of gridview. There are several number of controls like gridview provided by the ASP.Net which are very easy of use.

Difference Between asp.net and asp:-

1. Asp.Net is compiled the code first and then interpret is but the ASP was interpreted.
2. ASP.Net is Fast because of JIT compiler and not all code compile first time. With JIT whenever a code need to compiled the compiler compile it just in time, but in ASP this feature was not available.
3. You can separate your HTML and logic code into ASP.Net by using code behind files but in ASP this facility was not available and you should embed your ASP code with HTML.
4. ASP.Net is pure object oriented technology but ASP was a partially object oriented technology.
5. ASP.Net provide the in built XML support whereas ASP was not.
6. ASP.Net could be run on None Microsoft Web Servers like apache servers but ASP was not.
7. ASP.Net supports more languages to developed the web applications but the ASP was support only VB and C#.
8. The ASP.Net save the view state of a page controls for future use of its value but ASP was not has this technique.

Ajax with ASP.Net

How to Search an Element into a ListBox By Typing into aTextbox using javascript


How to Search an Element into a List Box using javascript in ASP.Net


Searching an Element into a List Box using JavaScript by Typing into TextBoxin Asp.Net:-


The Asp.Net ListBox is a server side control and there are no way to search Element into a list by typing the value into textbox, because the TextBox server control does not have any event to do this and the TextChanged event of TextBox is not working in this because when we trying this then it will reload the page and the selection of element into ListBox is gone again and it will come into previous state. So to do this we need to create a javascript function and call it onkeyup event of the TextBox and this will help you to select an element just typing the few first char into the textbox.

This is the Code for searching and selecting an element into ListBox by Typing TextBox.

<script type="text/javascript">
 function SearchList(obj,key,list)
    {    

    var tb="";
    tb+=obj.value;
    if(obj.value=="")
    {
        list.selectedIndex=-1;
    }
    else
    {
         for(var i=0;i<list.options.length;i++)
         {
             if(list.options[i].text.toLowerCase().substring(0,tb.length)==tb)
             {
                 list.options[i].selected=true;
                 if(key.keyCode==13)
                 {
                    obj.value=list.options[i].text;
                 }
                 return false;
             }
            else
            {
                list.selectedIndex=-1;
            }

        }
    }
    }  

</script>

call above function like this...

<asp:TextBox ID="text1" runat="server" onkeyUp="SearchList(this,event,document.getElementById('list1'))"></asp:TextBox>
<asp:ListBox ID="list1" runat="server"></asp:ListBox>


Types of Ajax in ASP.Net, How to call server side method using javascript


AJAX in ASP.Net

JQuery is a JavaScript library which is going to be popular day by day because of its large number of built-in functions and events which are used to make the light weight web applications with minimum amount of effort and time. The JQuery is simple and easy of use and provide the great compatibility of web programming languages. JQuery goint to be popular because of its provide the simplest and fastest way of using AJAX with web applications. The ASP.Net supports the various ways to use the AJAX like with Ajax.dll, with ScriptManager, with JavaScript and with JQuery.

Ajax with JQuery is the most quickest way to use ajax. In this tutorial i will teach you how to implement these all techniques with Ajax.

Ajax with Ajax.dll:- This technique was introduce in .net framework 1.0 and was depricated in 3.0 because microsoft introduce Ajax controls in the asp.net. This is a technique which was popular in 1.0,2.0 versions of .net framework and you can able to call server side methods into javascript code and pass and retrieve the value from the server side methods.
To do this you need to add the Ajax.dll file into your project like this 
step 1- Download Ajax.dll and save it anywhere into your hard drive.
step 2- right click on your project from solution explorer and click on add reference and browse the Ajax.dll file from your hard drive.
step 3- now go to web.config file and add this line into the <httpHandler> tag.
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
step 4- now register your class for ajax like this .
     protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(Ajax1));
    }


step 5- now create your method which you want to call into javascript like this.

   [Ajax.AjaxMethod()]
    public int sum(int x, int y)
    {
        return x + y;
    }
the [Ajax.AjaxMethod()] is compulsory for every method which you want to call using javascript.

step 7- now design your asp page drag and drop two textboxes and a button.
step 6- now you are ready to call the server side method from javascript.
function sum() {

        var a = document.getElementById("TextBox1").value;
        var b = document.getElementById("TextBox2").value;
      Ajax1.sum(a,b,gresult,gerror);         
        return false;
    }
    function gresult(res) {
            alert(res.value);
        }
        function gerror(er,text,status) {
            alert(er.value);
        }

the gresult is a function which handles the response and the gerror is a function which handles the error.
the gresult and gerror are not compulsory you can rename the name of these two according to your need.
call the javascript's sum function OnClientClick of button.

Ajax with SriptManager:- The script manager is another technique to call the server side methods into javascript. It was introduce in .net framework 3.0. To do this you need to use the System.Web.Services into your project and whenever you want to call the server side method into javascript you need to tell the compiler that the perticular method is of Ajax method like this.
step 1- use the webservices 
using System.Web.Services;

[WebMethod]
public static int sum(int a, int b)
    {
        return a + b;
    }

the static keyword is compulsory for this with methods definition.

step 2- now drag and drop two textboxes and a button into your aspx page.
step3- now write the following code into your javascript block.
function sum() {
            var a = $get("TextBox1").value;
            var b = $get("TextBox2").value;
            PageMethods.sum(a, b, gsuccess, gerror);
            return false;
        }

        function gsuccess(a)
        {
            alert("res="+a);
        }

        function gerror(er) {
            alert("error="+er.get_message());
        }

the $get() is same as the document.getElementById() methods and the gsuccess and gerror are doing same thing as above technique we have discussed.

Ajax with javascript:- This technique is quite simple and more fast then the above methods but it seems lengthy then above methods. If you want to do this you need to create a separate aspx  page which handles your server side code and you can call it from javascript and pass and retrieve values into it like this.

step 1- create an aspx page and write your server side code 

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Ajax1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int x=Int32.Parse(Request["a"].ToString());

        int b=Int32.Parse(Request["b"].ToString());
        Response.Write((a+b));
      }

}

step 2. Now create your javascript code. The javascript code is divided into three parts first for get browser object, second one is a request block and third one is handling response from the server, now we are discuss on among three in details.
getting browser object:-

function getObj()
{
var http;
if(window.XmlHttpRequest)
    http=new XmlHttpRequest();
else
    http=new ActiveXObject("Microsoft.XMLHTTP");
return http;
}

creating a request block:-

var https=getObj();

function sum()
{
 var a = document.getElementById("TextBox1").value;
 var b = document.getElementById("TextBox2").value;

var url="Ajax1.aspx?a="+a+"&b="+b;
https.open("GET",url);
https.onreadystatechange=HandleResponse;
https.send(null);
}

creating a response handling block:-

function HandleResponse()
{
if(https.readyState==4&&https.status==200)
{
  alert("sum="+https.responseText);
}
}

Ajax with JQuery:- This is the fastest and simplest way to use Ajax with JQuery API. To do this you need to create a server side method into any page of your website and you are able to call that method using JQuery. 

Step 1- Create a Method into any aspx.cs page like this

[System.Web.Services.WebMethod]
    public static int sum(int a, int b)
    {
        return a + b;
    }

Step 2- now drag and drop two textboxes and a button into your aspx page.
Step 2- Now write your JQuery code to call this method like this.

$("#Button1").click(function (e) {

                var a = $("#<%=TextBox1.ClientID%>").val();
                var b = $("#<%=TextBox2.ClientID%>").val();
               
                $.ajax({
                    type: "POST",
                    url: "ajaxwithscript.aspx/sum",
                    data: "{'a':'"+a+"','b':'"+b+"'}",
                    contentType: "application/json",
                    success: function (data) {
                    alert("ans=" + data.d);
                                                           
                     },
                 failure: function (data, b, c) { alert("error=" + b.responseText); }
                });

               return false;                

});