SAJAX And PHP

SAJAX (Simple Asynchronous JavaScript and XML) is an Ajax framework that lets you code Ajax JavaScript on the server by using various server-side languages like PHP, Perl, ASP, Python, and JSP etc. It is a tool written purely on PHP which helps to integrate JavaScript at server side with PHP code. The most recent version 0.12, you can download it from clicking on here. http://www.modernmethod.com/sajax/sajax-0.12.tgz


After downloading SAJAX toolkit, copy the SAJAX files to your project folder. Then create a file named testSajax.php and include the sajax.php file in it.

This example allow you to enter two values and click the Calculate button, the page uses SAJAX to calculate the sum of 2 values on the server and display the result without a page refresh.



Code:

<?
Require(�sajax.php�)
?>


Write a php function to return the sum of 2 variables.


Code:

function add($val1, $val2) {
  return $val1 + $val2;
}


Then set up Sajax by calling sajax_init, and export the add function using the Sajax built in method sajax_export():


Code:
sajax_init();
sajax_export(�add�);


Call the sajax_handle_client_request method

Code:
sajax_handle_client_request();


Sajax generates the JavaScript needed in this example by calling PHP

Code:
function sajax_show_javascript
sajax_show_javascript();



Full Source Code ( testSajax.php )



Code:
<?
 require("Sajax.php");
 function add($val1, $val2) {
  return $val1 + $val2;
 }
 sajax_init();
sajax_export("add");
 sajax_handle_client_request();
?>
<html>
<head>
<script>
 <?
 sajax_show_javascript();
 ?>
 function scriptToadd_result(z) {
  document.getElementById("textbox3").value = z;
 }
 function scriptToadd() {
  var val1, val2;
  val1 = document.getElementById("textbox1").value;
  val2 = document.getElementById("textbox2").value;
  x_add(val1, val2, scriptToadd_result);
 }
 </script>
</head>
<body>
 <input type="text" name=" textbox1" id=" textbox1" value="2" size="3">
 +
 <input type="text" name=" textbox2" id=" textbox2" value="3" size="3">
 =
 <input type="text" name=" textbox3" id=" textbox3" value="" size="3">
 <input type="button" name="check" value="Calculate"
  onclick="scriptToadd(); return false;">
</body>
</html>


When you run this script you will see Ajax code in action.

If you have any comments about this article please post your comments here.

Commentaires

Posts les plus consultés de ce blog

XAJAX with PHP – The future of web development

XAJAX with PHP – The future of web development

Database connection pooling in ADO.Net