hientx

Just another WordPress.com site

Category Archives: ajax

Hello Jsp and Ajax

Simple Ajax script for JSP

Lot of script is available for auto complete, load page, validation, and menu navigation in Ajax which can use in JSP.

A simple example of ajax show you to use in JSP

index.jsp

<html>
<head>
<script src=”ajaxjs.js”></script>
</head>
<body>
<a href=”javascript:loadContent(‘parameterValue’)”>Load Ajax content</a>
<div id=”prtCnt”></div>

</body>
</html>

ajaxjs.js

var xmlhttp

function loadContent(str)
{

xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)
{
alert (“Your browser does not support Ajax HTTP”);
return;
}

var url=”loadJSP.jsp”;
url=url+”?q=”+str;

xmlhttp.onreadystatechange=getOutput;
xmlhttp.open(“GET”,url,true);
xmlhttp.send(null);
}

function getOutput()
{
if (xmlhttp.readyState==4)
{
document.getElementById(“prtCnt”).innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject(“Microsoft.XMLHTTP”);
}
return null;
}

JSP file which load in background

loadJSP.jsp

<%@ page contentType=”text/html; charset=iso-8859-1″ language=”java” %>
<%
String q =request.getParameter(“q”);
String str=”This is JSP string loading from JSP page in ajax, loading time :”;
java.util.Date dt=new java.util.Date();
out.print(str+dt);
%>

source: easywayserver

AJAX XMLHttpRequest

– File HelloAjaxHttpRequest.html

<html>
<head>
<title>Aborting ajax requests</title>
<style type=”text/css”>
ul{border:1px solid black; list-style:none;
margin:0pt;padding:0pt;float:left;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;width:300px;}
li{padding:10px 5px;border-bottom:1px solid black;}
</style>

<script type=”text/javascript” src=”../js/jquery.js”></script>
<script type=”text/javascript”>
$(document).ready(function ()
{
var ajax;
$(‘#choice’).change(function()
{
if(ajax)
{
ajax.abort();
}
ajax = $.get(
            ‘wait.php’,
            { what : $(this).val() },
            function(response)
            {
              $(‘#response’).html(response);
            },
            ‘html’
          );
});
});
</script>

</head>
<body>
<form>
<p>
Show list of:
<select id=”choice”>
<option value=””>select</option>
<option value=”good”>Good Guys</option>
<option value=”bad”>Bad Guys</option>
</select>
</p>
<p id=”response”></p>
</form>
</body>
</html>

– File wait.php

<?php
  sleep(2);
if($_GET[‘what’] == ‘good’)
{
$names = array(‘Sherlock Holmes’, ‘John Watson’, ‘Hercule
Poirot’, ‘Jane Marple’);
echo getHTML($names);
}
else if($_GET[‘what’] == ‘bad’)
{
$names = array(‘Professor Moriarty’, ‘Sebastian Moran’,
‘Charles Milverton’, ‘Von Bork’, ‘Count Sylvius’);
echo getHTML($names);
}
function getHTML($names)
{
$strResult = ‘<ul>’;
for($i=0; $i<count($names); $i++)
{
$strResult.= ‘<li>’.$names[$i].'</li>’;
}
$strResult.= ‘</ul>’;

return $strResult;
}
?>

All AJAX methods of jQuery return an XMLHttpRequest object when called. We have declared a global variable ajax that will store this object. When a value is selected from the combo box, the handler function checks if the variable ajax is defined or not. In case of the first selection it will be undefined, hence nothing happens and the request is sent to the wait.php file. The XMLHttpRequest object created for sending this request is stored in variable ajax.

Now when a value of combo box is changed ajax will be holding the XMLHttpRequest object that was used to send the previous request. XMLHttpRequest has an abort() method that cancels the current request. In our case the pending request to the server is cancelled and a new request is made, which is again stored in the ajax variable.

Compare Post and Get

$.post() is almost similar to $.get() except for a couple of differences. The first, and obvious difference, is the method used which is POST for $.post() and GET for $.get(). The second difference is that POST requests are not cached whereas GET requests are cached by the browser. Therefore, the use of the cache option with POST request will have  no effect on the request.

Other than that, both $.get() and $.post() have the same signatures.

Hello PHP AJAX using jQuery

Create 2 files in the same folder:

Example 1:

– File: helloAjax.html

<html>
<head>
<title>jQuery.get()</title>
<style type=”text/css”>
ul{border:1px solid black; list-style:none;
margin:0pt;padding:0pt;float:left;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;width:300px;}
li{padding:10px 5px;border-bottom:1px solid black;}
</style>

<script type=”text/javascript” src=”../js/jquery.js“></script>
<script type=”text/javascript”>
$(document).ready(function ()
{
$(‘#choice’).change(function()
{
if($(this).val() != ”)
{
$.get(
data.php‘,
{ what: $(this).val() },
function(data)
{
$(‘#result’).html(data);
});
}
});
});
</script>

</head>
<body>
<form>
<p>
Show list of:
<select id=”choice”>
<option value=””>select</option>
<option value=”good”>Good Guys</option>
<option value=”bad”>Bad Guys</option>
</select>
</p>
<p id=”result”></p>
</form>
</body>
</html>

– File data.php

<?php
if($_GET[‘what’] == ‘good’)
{
$names = array(‘Sherlock Holmes’, ‘John Watson’,
‘Hercule Poirot’, ‘Jane Marple’);
echo getHTML($names);
}
else if($_GET[‘what’] == ‘bad’)
{
$names = array(‘Professor Moriarty’, ‘Sebastian Moran’,
‘Charles Milverton’, ‘Von Bork’, ‘Count Sylvius’);
echo getHTML($names);
}
function getHTML($names)
{
$strResult = ‘<ul>’;
for($i=0; $i<count($names); $i++)
{
$strResult.= ‘<li>’.$names[$i].'</li>’;
}
$strResult.= ‘</ul>’;

return $strResult;
}
?>

Example 2:

File helloAjax2.html

<html>
<head>
<title>Detecting AJAX Requests</title>
<script type=”text/javascript” src=”../js/jquery.js”></script>
<script type=”text/javascript”>
$(document).ready(function ()
{
$(‘input:button’).click(function()
{
$.get(
‘check.php’,
function(data)
{
$(‘input:button’).after(data);
});
});
});
</script>

</head>
<body>
<form>
<p>
<input type=”button” value=”Load Some data”/>
</p>
</form>
</body>
</html>

File check.php

<?php

// Browsers send HTTP headers with every request that goes to a server. To distinguish between
// normal requests and AJAX requests, modern libraries send an additional header with AJAX
// request. The header’s name is X-Requested-With and its value is XMLHttpRequest.

if(isset($_SERVER[‘HTTP_X_REQUESTED_WITH’]) &&  $_SERVER[‘HTTP_X_REQUESTED_WITH’] == ‘XMLHttpRequest’)
{
echo ‘YaY!!! Request successful.’;
}
else
{
echo ‘This is not an AJAX request. This page cannot be
accessed directly.’;
}
?>