Now days I’m working on a web project. So I decide to tell you some modern web techniques regarding Web Developing.
Now a days one of the most popular plugin is a Jquery plugin so in here I’m explaining how to use Jquery with Ajax.
If we want to get some data from the user in webpage the best way is to use html <form> tag but case is if we using normal Ajax we have to write long java script to handle that ajax object but if we use Jquery we have to write only few lines of code to do it .Other thing is we can send whole form using one line of code.
Lets see how to do it. This is my JSP file name is Index.jsp it has simle form and when user click calculate button result will show in result textbox without refresing a page.
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax with Jquery</title> </head> <body> <h1>Ajax with Jquery Simple Example</h1> <h3>madushankaperera.wordpress.com</h3> <br> <form name="form1" method="GET" action="Ajaxexample" id="form1"> <table> <tr> <td>Number 1</td><td><input type="text" name="n1"/></td> </tr> <tr> <td>Number 2</td><td><input type="text" name="n2"/></td> </tr> <tr> <td></td><td><input type="submit" value="Calculate"/></td> </tr> <tr> <td>Result</td><td><input type="text" value="" id="result"/></td> </tr> </table> </form> </body> </html> <script type="text/javascript" src="js/jq.js"></script> <script type="text/javascript"> var form = $('#form1'); form.submit(function () { $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), success: function (data) { var result=data; $('#result').attr("value",result); } }); return false; }); </script>
I have use Jquery Ajax method to deal with the Ajax.First I’m getting the form element in html tag to javascript variable
called “form” then I’m passing it to my servlet using Ajax. Then getting return value from servlet and dispaly it on page
In this example getting the 2 values from the user and pass it to java servlet and calculate the sum and display it on a page
here is my Java Servlet name is “Ajaxexample.java”
package com.servlets.cal; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author madushanka */ public class Ajaxexample extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); int n1 = Integer.parseInt(request.getParameter("n1")); int n2 = Integer.parseInt(request.getParameter("n2")); out.println(n1 + n2 + ""); } }
My web.xml file
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>Ajaxexample</servlet-name> <servlet-class>com.servlets.cal.Ajaxexample</servlet-class> </servlet> <servlet-mapping> <servlet-name>Ajaxexample</servlet-name> <url-pattern>/Ajaxexample</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app>
Actually this is very easy method to submit form data with Ajax you can use this with even PHP also .
Great JOB …..AWESOME….Thanks A Lot
Welcome friend !!
Not working this code. where is this filehttp://js/jq.js
Jst download the latest jquery plugin and rename it as jq.js
this doesnt work. the browser is redirecting to the servlet url
It means something wrong with your jquery method or jquery plugin
form.submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
Can u help me with upload image use servlet
This article might be helpful to you.
http://www.roseindia.net/servlets/upload-image.shtml
Thanks a lot
I’m from VietNam and I speak and write English not good
If I write something incorrect please forgive me 🙂
After search in google now I know how to upload image but in my project have some problem
that when I upload image success it display image but refresh page and all information I write in that page will lost.Can you tell me some way to fix that
You are welcome friend 😀 nice to meet you .It doesn’t matter because we all are not perfect 100% 😀
The thing is HTTP is stateless protocol . It means it wont keep your data all the time.
When you refresh the page it means you are requesting your page again but HTTP is considered that as new request there for it will show you a clean page without your old data.
If you want to refresh part of your page without refreshing your whole page you can use Ajax or Jquery load() method .
Yes many people told me that i can use ajax to deal with my problem
But I don’t know how to use ajax to load a image.I don’t know anything about ajax just a litter bit about jquery
In my project after I finish upload image I save image name in seesion.Can you tell me how can I display image from source like this
<%
if (session.getAttribute("imageUrl") != null) {
out.print("New Product Image”);
%>
<img style='padding:10px 10px' width='100px' height='90px' src="${pageContext.request.contextPath}”/>
your src should be
<img style='padding:10px 10px' width='100px' height='90px' src="${pageContext.request.contextPath}/images/your image name.png ”/>
yes It correct.Your comment form don’t have enough space
<%out.print("”);%>
But how to use ajax to avoid loading page again
<img style='padding:10px 10px' width='100px' height='90px' src="${pageContext.request.contextPath}”/>
something wrong with your blog
It erase a part of my comment
Do not forget this is also a web page there for your comment also considered as codes
there for use code tags to insert codes into comment
Hi How will this work if I have a Form Bean associated with the Form in the jsp ?
Same method but inside the servlet you have create object using your bean class and set data to that object using your form data.
I pressed the button and doesn’t work, I haven’t could implemented any exercise taught on internet. I don’t know what I could be doing bad. Or Maybe Is it the JQuery library?. In this example, I press the button and appears other page with the result, but does’nt appear into the input with id=result.
I’m working with PURE SERVLETS, no struts, no spring.
Thanks but the result is not printing
both of you have to import jquery plugin into your html page
see line 30 of my html page example
src = ” path to your jquery plugin ”
why do you use Interger.parseInt…
Integer.parseInt(request.getParameter(“n1”));
you can’t just go int n1 = request.getParameter(“n1”);
you need to parse the parameter as an int. In a request the parameters are just strings
so you need to interpret it on the server as the type you expect.
what is the code inside jq.js?
it is jquery plugin
you can download it from jquery website if you want use jquery inside your project you have to import that jquery plugin into your project
https://code.google.com/p/js-files-tools/downloads/detail?name=jq.js&can=2&q=
is it a appropriate js file
Go to jquery web site then download file.
Hi, i need to get a result with out any submit button.. like if user enter in number1 and number2 without clicking any button it should display the output in result field.. so please help me
Use focus lost method in jquery
$(“#number 2 text field id”).blur(function(){
// ajax code
});
I need to get value of a dynamic list without submitting the form..
I would suggest you use a GSON library for doing that and in you servlet have something of the following for the request:
List people=new ArrayList();
people.add(new Person(“sneha”,”sneha”));
people.add(new Person(“razaractor”,”razaractor”));
String json = new Gson().toJson(people);
response.setContentType(“application/json”);
response.setCharacterEncoding(“UTF-8”);
response.getWriter().write(json);
I have a jsp and i need to pass a value from that jsp to servlet without submitting that form as i am opening a pop up window from that form and refreshing the parent form again after doing required action. Can somebody suggest me how to proceed…
Thank you very much for the great example.
You’re Genius.
Thanks a lot man. I spent the whole day googlin for such solution
Exactly what i need
Thanks
Dude… Your jquery code written in Script is not required at all and without this jquery code this code is working but result is getting displayed on other page not on same page in result field, Because you are using Action=”Ajaxexample”. I want to use Jquery Post method written in script and i dont want to use Action=”Ajaxexample” on form. I removed the action from the Form and trying to implement this post mehtod by jquery only but till now i am not able to get success. n1 and n2 values are not getting post to Ajaxexample servlet at all 😦
Below is the function which i am using.
$(document).ready(function() {
$(“#Submit”).click(function () {
alert(“inside click function”);
$.ajax({
url: “http://localhost:8082/JQuery_Test/AjaxExample”,
type: “POST”,
success: function(response) {
return alert(“Hey”);
},error: function(errorData){
alert(errorData+””);
}
});
alert(“Exiting”);
} );
Both alert are working but i checked values on Ajaxexample servlet and the n1 and n2 values are not getting posted on that servlet.
});
I am wondering, if i am putting this script in head tag then result is getting displayed on new page but if i am putting this script after body tag then its giving result in the defined text box. Can anyone tell me why its behaving differently in both these cases. As per my understanding we can keep the script tag either in body or head but it should behave similar in both the cases.
Where should i save the web.xml file? Also why we have not mentioned about the xml file anywhere in the code
Your Project Name /web/WEB-INF/web,xml
this is the path to web.xml file but if you are using netbeans no need to do it yourself because it will generate automatically.
Thanks for the response.
Now, the problem is when i press calculate the result is printed on another page instead of the result box
i think there might be something wrong with your Ajax script .
Ajax call back function displaying send data instead of response..
Sir plz help me…
1st of all check your jquery method all variable names etc then check your servlet put sout and check all the input and outputs
It showing me the whole page(form) which I sent instead of showing me result from servlet…
Showing the same page means your jquery function wont work. Recheck it
hi i want to send a jsp form to to a servlet with ajax the result of thar servlet will be send to another jsp, in order to stay on the first jsp form jsp
request.getRequestDispatcher(”
file.jsp”).forward(request,
response);
You can simply use this method inside servlet
Hi I need sourcecode for validating username in registration form.
Can you please help me for that?
Use javascript method
Hey friend , I tried your code above(copy pasted all the codes actually hihihi ), but when I tried to click the calculate button the result was displayed in the other page not the same with what’s in your video though. Please help T__T
and what’s the use of jq.js then? was it the jquery plugin?
Yes friend
something wrong with your jquery code
recheck again 😀
Can you post the jq.js pls, cause when i click on calculate submit that display result in another page, i’m sure that i have the same code but it doesnt work.. Please help me
Jq.js means jquery plugin just download ir from jquery website
y cant u just upload jq.js file
It is just a jquery plugin you can download it from the jquery official website
how can i get content of jsp page using ajax
what you mean by content ?
thank you its useful for me.
thanks sir for this article..
but if i dont want to use jquery plug in. i want to use only ajax to submit form with both validation server and client with appropriate result on text boxes. pls suggest me is it possible or not ?
You can use ajax without jquery use simple javascript
how to get that data which is in success function to servlet
you need to do is get the PrintWriter object from the response and write data to it and that will available in the success function .
Hi,after i implemented your code,my page still proceed to the action url.How can I submit the form without directing my page to action url?
Is there a way to submit form without refreshing the page without using Ajax? If so i need example
I dont think so 😀 you can even use jquery only but inside of that jquery function also use ajax 😀
develop spring mvc example for employee registration login and profile view. shd use spring mvc and JDBC..
Your code is not working , I think problem with jquery.
jquery script is not called while submitting the form
Sorry bro,
Its working
I am new to ajax. Your code is working. Simple and Superb solution Madushanka perera!! In fact i feel you are a person of calibre and would like to offer part time work to you!!
please give code for js/jq.js..
i have pass td as input in table and its value to be inserted in DB..
please help
jq.js means jquery plugin downloaded from jquery website