Setelah kita telah membuat
file ajax.js,
yang digunakan validasi fungsi dari ajax
Selanjutnya,
kita membuat file javascript (bukan java),
yang terkait pada script dept_form.html,
yaitu
<script src=”dept.js” type=”text/javascript”></script>
File yang bernama dept.js (penamaan bebas),
berfungsi untuk perantara fungsional AJAX,
dengan PHP, dimana PHP yang akan mengakses database (MySQL).
Berikut script dari dept.js
// dept.js
// Have a function run after the page loads
window.onload = init;
// Function that adds the Ajax laver
function init()
{
// Get an XMLHttpRequest Object
var ajax = getXMLHttpRequestObject();
// Attach the function call to the form submission, if supported
if(ajax)
{
// Check for DOM support
if(document.getElementById(‘results’))
{
// Add an onsubmit event handler to the form
document.getElementById(‘dept_form’).onsubmit = function()
{
// Call the PHP scripts
// Use the GET method
// Pass the department_id in the URL
// Get the department_id
var did = document.getElementById(‘did’).value;
// Open the connection
ajax.open(‘get’, ‘dept_results_ajax.php?did=’+encodeURIComponent(did));
// Function that handles the response
ajax.onreadystatechange = function()
{
// Pas it this request object
handleResponse(ajax);
}
// Send the request
ajax.send(null);
return false; // So form isn’t submitted
} // End of anonymous function
} // End of DOM check
} // End of Ajax IF
} // End of init() function
// Function that handles the response from the PHP scripts
function handleResponse(ajax)
{
// Check that the transaction is complete
if(ajax.readyState == 4)
{
// Check for a valid HTTP status code
if((ajax.status == 200) || (ajax.status == 304))
{
// Put the received response in the DOM
var results = document.getElementById(‘results’);
results.innerHTML = ajax.responseText;
// Make the results box visible
results.style.display = ‘block’;
}
else
{
// Bad status code and submit the form
document.getElementById(‘dept_form’).submit();
}
} // End of readyState IF
} // End of handleResponse() function
Sambil mengetikan script,
serta mempelajari,
jika masih ada yang belum dipahami,
silakan ditanyakan,
sambil saya mempersiapkan langkah2 selajutnya
hehehe
Semoga Bermanfaat.
Salam dari Cirebon,
Rony Syahputra N.