Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Wednesday, 27 November 2013

Autocomplete HTML Input Field using JSP and JQuery in Five Lines!


Everyone is fascinated about auto-complete. Right? I think, Are you? Drop in the comment below. Long time I've been connecting JQuery and Java and have some of the posts like loading JSP file in JQuery in one line Now, it is time to go further.

I would be blogging now a simple example on how to connect auto-complete for a HTML text field to a JSP file with JQuery in one line! Yes, in five lines!, YOU heard it RIGHT!

Project structure

Folder path: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_autocomplete



jq_autocomplete

                |

                +-- index.html

                +-- auto.jsp

index.html - HTML file



<html>
    <head>
        <title>Send POST Request to Servlet with JQuery</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
                // When any key is down
                $(document).keydown(function(){

                    // Get the input element and its value
                    var i=$("#com");
                    var val=i.val();

                    // Send request only if user types alphabet
                    // because auto.jsp returns names of companies
                    // which contains only alphabets
                    if(val.match(/^[A-z]+$/))
                    {
                        // Send request and get the data
                        $.get("auto.jsp?com="+val,function(data){

                            // Get each item separated by new line
                            var items=data.split("\n");

                            // put those items in autocomplete! That's it!
                            i.autocomplete({source:items});
                        });
                    }
                   
                });
        </script>
    </head>
   
    <body>
        <input type="text" id="com" name="com"/>
    </body>
</html>

The point here is that the function keydown is executed every time when a key is down in the document and so the request will be sent each time when the key is down degrading performance of the application. To avoid this, the if-condition is useful which checks if the value matches the regex which corresponds to any alphabet.

auto.jsp - Returns auto complete data



<%@page import="java.util.*"%>
<%
    // Create ArrayList and add some items
    ArrayList<String> as=new ArrayList<String>();
    as.add("Google");
    as.add("Yahoo");
    as.add("Apple");
    as.add("Microsoft");
    as.add("Linkedin");
    as.add("Facebook");
    as.add("IBM");
    as.add("Oracle");
    as.add("Salesforce");
    as.add("Amazon");
   
        String s=request.getParameter("com");
       
            for(String st:as)
            {
                if(st.toLowerCase().startsWith(s.toLowerCase()))
                {
                    out.println(st);
                }
            }
%>

The best price you could pay for this post is sharing it. I thank you in advance :)
Photo Credit: Angelina :) via Compfight cc

Monday, 25 November 2013

Send POST Request to Servlet in JQuery in One Statement!

Post request with JQuery
Here is a single-line statement to send a POST request to a servlet with JQuery. This is gonna be dead simple. Yes, so simple that it is nothing more than a JQuery method call. Curious about what the method is? Me too! It is none other than..

post(): There are a lot of versions of this method. But here, we are going to use the simple version which takes the url-pattern and the data to be submitted.

Project structure

Folder: D:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_post


jq_post
        |
        +-- index.html
        +-- WEB-INF
                    +-- classes
                            +-- simple.java
                            +-- simple.class

index.html


<html>
    <head>
        <title>Send POST Request to Servlet with JQuery</title>
        <script src="http://code.jquery.com/jquery-2.0.0.js"></script>
        <script>
            $(function(){
           
            $( "#hform" ).submit(function(event) {
           
                // Stop form from submitting normally
                event.preventDefault();
               
                // Get some values from elements on the page:
                var form = $(this);
               
                // Get the value in input uname
                term=$("input[name='uname']").val();
               
                // Send the data using post
                var posting = $.post("hello",{uname:term});
               
                    // When the POST request is done..
                    // data: The output printed in servlet
                    posting.done(function(data) {
                       
                        // Put the results in a div
                        $("#view").append(data+"<br/>");
                       
                    });
            });
            });
        </script>
    </head>
   
    <body>
   
        <!--Create the form-->
        <form id="hform" action="/jq_post/hello" method="post">
            <input type="text" name="uname"/>
            <input type="submit" value="SUBMIT"/>
        </form>
        <!--Create the form-->
       
        <div id="view"/>
    </body>
   
</html>

web.xml - Deployment descriptor



<web-app>
    <servlet>
        <servlet-name>ser</servlet-name>
        <servlet-class>simple</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>ser</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Related: What is web.xml in servlets?

simple.java contains doPost()



import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class simple extends HttpServlet
{
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
        // Get the user name from html input field
        String name=req.getParameter("uname");
       
        // Get PrintWriter obj using getWriter() in HttpServletResponse
        PrintWriter pw=res.getWriter();
       
        // Print, that's it!!
        pw.println("Hello "+name+"!");
    }
}

Image credit: tuicool.com

Saturday, 23 November 2013

Load a JSP File using JQuery in One Line


Here is how to load a JSP file using JQuery in a single line!. The following is a hello world JSP example which will be loaded on a button click using the JQuery. As you can see from the image, the paradigm, write less, do more. is exactly exemplified here.

Project structure

Folder: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_jsp

jq_jsp

    |

    +-- index.html

    +-- hello.jsp


index.html




<html>


<head>


<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


<script>


// When the document is ready..


$(document).ready(function(){


// When any element with input tag is clicked


// execute the following function


$("input").click(function(){


// Get object of element with loadHere id


// And in it load the hello.jsp file!


$("#loadHere").load("hello.jsp");


});


});


</script>


<title>Load a JSP File in JQuery</title>


</head>




<body>


<input type="button" value="Get hello"/>


<div id="loadHere"/>


</body>


</html>


hello.jsp




<%


response.getWriter().println("Hello world!");


%>


The greatest appreciation you could give me is sharing this article. I would sincerely appreciate it :)

Friday, 22 November 2013

Submit a Form to Servlet using JQuery

Here is how to submit a form in background to servlet using JQuery in one single line. The scope of the program is to print a hello message in a html div. Note that you need to have a basic knowledge of JQuery and Javascript to understand this. But I'm pretty sure that the helpful commentaries will give you an understanding even if it is your first sight :)

Folder structure

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\jqform

Project structure



jqform


|


+-- index.html


+-- WEB-INF


+-- web.xml


+-- classes


+-- simple.java


+-- simple.class


HTML Files

index.html




<html>


<head>


<title>JQuery - Servlet form submission</title>


<!--To use jquery, loading this is mandatory-->


<!--If you don't have internet connection, download this file


and give the local path


-->


<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


<script>


// When the page is loaded, then..


// execute this function


$(document).ready(function(){




// When the button with id submit


// is clicked, this function should


// be executed


$("#submit").click(function(){


// Get the value in the val field


var val=document.getElementById("t").value;




// Now, get the element with id displayMsg


// and in it load the given file


// The text printed in the servlet class now


// comes in the displayMsg div


$("#displayMsg").load("/jqform/go?q="+val);


});


});


</script>


</head>




<body>


<input type="text" name="q" id="t"/>


<input type="button" id="submit" value="SUBMIT"/>


<div id="displayMsg"/>


</body>




</html>


Here, the load() method takes a string which corresponds to the page that is to be loaded. Here, we are indirectly calling the page http://localhost:8080/jqform/go?q=gowtham (when you type 'gowtham' in the input field) and that the content in the page is pasted in the displayMsg division. In other words, simply, the above page is loaded in the div instead of a new page. That's it.

Deployment Descriptor

web.xml




<web-app>


<servlet>


<servlet-name>puppy</servlet-name>


<servlet-class>simple</servlet-class>


</servlet>




<servlet-mapping>


<servlet-name>puppy</servlet-name>


<url-pattern>/go</url-pattern>


</servlet-mapping>




</web-app>


Servlet Programs

simple.java




import javax.servlet.*;


import javax.servlet.http.*;


import java.io.*;


public class simple extends HttpServlet


{


public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException


{


String q=req.getParameter("q");




// Get write object and print


PrintWriter pw=res.getWriter();


pw.println("Hello "+q);


}


}