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.’;
}
?>