Saturday, October 6, 2012

Simple Ajax with JQuery

First I will write code with native Ajax then will write same code using Ajax.

The code below for add two number. There will be two text box on jps page and user has to enter first number and click on Add button then it will add first text box and second box number and will be showed to second text box. One clear button is also there to clear both text boxes.

Back side (Server side) will be came in both ways.

Pure (Native) Ajax:

var request;

function getRequest(){
        request = new ActiveXObject("Microsoft.XMLHTTP"); 
       }else if(window.XMLHttpRequest){
        request = new XMLHttpRequest(); 

function addAction(){
 var first = document.getElementById("firstNumber").value;
alert("Please enter first number");
return null;
 var second = document.getElementById("secondNumber").value;
second = 0;
 calculation(first, second, "add");

function calculation(first, second, operation){
 var url = "http://localhost:8080/Calculator/Calculator?first="+first+"&second="+second+"&operation="+operation;"POST",url,false);
 request.onreadystatechange = showResult;

function calculation2(first, second, operation){
var url = "http://localhost:8080/Calculator/Calculator";"POST",url,false);
request.onreadystatechange = showResult;
request.send("first="+first+"&second="+second+"&operation="+operation); // Why Null

function showResult(){

if(request.readyState == 4){
        var result = request.responseText;
        document.getElementById("secondNumber").value = result;

function clearInput(){

JQuery Ajax code:


var first = $('#firstNumber').val();
var second = $('#secondNumber').val();
alert("Pleae enter first number");

   type: 'POST',
   url: 'http://localhost:8080/Calculator/Calculator',
   async: false,
   data: {
   first: first,
   second: second,
   operation: 'add'
    success: getAjaxData


function getAjaxData(data){


JSP Page Code:

It is simple Calculator
<input type="text" id="firstNumber"/>
<input type="button" id="addButton" value="Add" onclick="addAction()"/>
<input type="text" id="secondNumber" readonly="readonly"/>
<input type="button" id="clearButton" value="Clear" onclick="clearInput()"/>

Server side Code:

String first = request.getParameter("first");
String second = request.getParameter("second");
String operation = request.getParameter("operation");"First Number :"+first);"Second Number :"+second);
int result =  Integer.parseInt(first)+Integer.parseInt(second);

For Ajax using DOJO

No comments:

Post a Comment

You can put your comments here (Either feedback or your Question related to blog)