PHP-AJAX

Using AJAX With PHP – The SAJAX Way

Right so the objective is to use PHP with AJAX to achieve what is normally known as “refresh less browsing”. When I started off with my work I had to deal with quiet a lot of forms which posted variables to a PHP page and then I could use them either by query string or whatever method to display them. The only problem with this was that the page had to be refreshed. I had a vague idea about AJAX but never really got into using it until I really got fed up of page refreshes, so if you share the same enthusiasm (slightly) this might prove helpful.

Besides the story above AJAX stands for Asynchronous JavaScript and XML. The objective of AJAX is to allow asynchronous transfer of data from the server to the client and vice versa without interfering with any of the stuff on the main page (page refreshes) and since JavaScript is executed on the client end and PHP code is executed on the server end (duh) we need a way to do that. How AJAX actually achieves that we’ll leave that discussion for another time. Now i have been searching for a library or something magical that makes my life easier. That’s when i came across SAJAX an open source library which does that something magical.

So what do you need:

1) PHP ( since we will be using SAJAX with PHP) whatever version I used 5 i don’t know if SAJAX works with other versions or not

2) SAJAX library can be found at : http://www.modernmethod.com/sajax/download.phtml download the zip file and extract it to wherever you need it

Now within the SAJAX there would be a number of folders. ASP, Coldfusion and others(Probably support for other platforms, you could’ve guessed that couldn’t you ! ). So there is another folder PHP open it and get the “SAJAX.php” file from there and paste it in the project or folder or wherever you wish to use it. Notice there are a few examples there as well if you can get a grip of it from it i guess this is the end of the line for you then 🙂 but if not continue reading.

Ok so now we have the library so lets begin. At the top of your PHP page include:

<?php require('Sajax.php'); ?>

Can be a include as well but a personal choice. Now the objective:

Send data from client to server – > Process it – > Return it to Client which is

JavaScript -> PHP -> JavaScript

So first we define a function in PHP which would be the worker or which would do something when invoked by the client, which means I’m effectively entertaining the middle part of the chain which I just mentioned above. Once you get the hold of it you can start off from anywhere. So I declare a function like:

<?php require('Sajax.php'); Function worker() { Return ‘hello world’; } ?>

Right so the function will simply worker function will simply return a hello world. Now we add some SAJAX stuff which actually export this function to JavaScript and make everything happen. After my function I stick in these lines:

$sajax_request_type = "GET";

sajax_init();

$sajax_debug_mode=1;

sajax_export("worker");

sajax_handle_client_request();

Now lets go through each of these lines. Firstly the request type, it works the same way as in normal forms, the GET method appends values to the URL and since the URL can only handle a limited number of parameters there is a possibility it might get truncated so its only used if the amount of parameters to be passed are less, simililary the fields such as passwords etc will be displayed if passed using the GET method. This can also be a “POST” request which would require changing the above to “POST” which appends all the values to the body of the HTTP request. Too much detail?. Anyway the second line sajax_init() initializes the library variables etc. The third line is a not so fancy debugger which outputs what happens behinds the curtains in the form of alert boxes set it to “0”if you don’t want to use it and set it to “1” if you want to use it or better just remove the line if you don’t care. The fourth line is and export call which tells the library this is the function we wish to export, export where? To the JavaScript so that we make use of it, how? We shall know it soon.

Notice however one thing no matter what type of function you have or whatever it takes as arguments you just have to put its name in the export and nothing else remember NOTHING ELSE JUST THE NAME. We shall see how we deal with arguments later on. The last line simply tells the library to get ready to handle requests from the client its like an automatic poller thing which checks for requests so now the overall code looks like this:

<?php require('Sajax.php'); function worker() { return 'hello World'; } $sajax_request_type = "GET"; sajax_init(); $sajax_debug_mode = 1; sajax_export("worker"); sajax_handle_client_request(); ?>

Now we call this function from our JavaScript, before that we need to stick a small line into our JavaScript code which is:

();
?>

This is something which just be done to make the function usable and I have nothing to do with it. Now lets call our JavaScript function which is done by:

();
?>

X_worker(callback);

Function callback(retArg)

{

Alert(retArg);

}

Ok so lets see what’s going on we had a function in PHP called worker no in order to call it from JavaScript we must append and “x_” to the name of the function we “exported” so it becomes x_worker if the export function was “test” then we call it using “x_test”. Within the function though there is no argument in the PHP function though in JavaScript I pass a call-back argument. This in fact is the function which would be called once the worker function is done doing its job so in this case the name is call-back and the returned argument from the PHP function is “hello world” so retArg alerts “hello world”

Ok some things to mention and try out:

1) Do not try to echo or use print statements within the PHP function if you try to do that, it will append the results with the return argument and give you an error “Cannot Eval” in the debugger.

2) When using the statements :

$sajax_request_type = "GET";

sajax_init();

$sajax_debug_mode=1;

sajax_export("worker");

sajax_handle_client_request();

Make sure you place them before any of your other “includes” because it would append them to the results and what you would see in your debugger is a

full HTML alert.The final code looks like this:

<?php require('Sajax.php'); function worker() { return 'hello World'; } $sajax_request_type = "GET"; sajax_init(); $sajax_debug_mode = 1; sajax_export("worker"); sajax_handle_client_request(); ?>

();
?>

X_worker(callback);

Function callback(retArg){

Alert(retArg);}

The next post will cover passing arguments from be it arrays, objects etc using the SAJAX. Feel free to post any questions and I will try to get back to you with answers.

4 thoughts on “Using AJAX With PHP – The SAJAX Way

  1. I am trying to setup my home server to use AJAX, I am using WAMP and using the php_json.dll extension, the problem is that when passing params they are not being sent, and also getting no return values, I assume this is a setting on my server can anyone enlighten me on this?

    Thanks,

    Shaun

  2. Hi Shaun can you please provide version details on the SAJAX and the WAMP server? Once you provide me with those I will try to replicate the problem and see how it goes

    Regards,

    Garagedeveloper

Leave a reply to garagedeveloper Cancel reply