Bellow is a javascript function I wrote to help process ajax actions because I was finding my self repeating a lot of the event trigger functions.
function processData(logicFile, container, action, id, form, onComplete){
var Options = new Array;
if(action != null) {
actionArray = action.split('~');
if(actionArray[0] != null){
Options.push('action=' + escape(actionArray[0]));
}
if(actionArray[1] != null) {
Options.push('sub_action=' + escape(actionArray[1]));
}
}
if(id != null) {
Options.push('id=' + escape(id));
}
if(form != null) {
var keyValueArray = form.split('&');
var i = 0
while (i < keyValueArray.length) {
Options.push(keyValueArray[i]);
i++;
}
}
if(onComplete == null) {
onComplete = function(data){
$(container).html(data.responseText);
}
}
$.ajax({
type: 'POST',
url: logicFile,
data: Options.join('&'),
complete: onComplete
});
}
Now here’s how it works.
Lets start with the variables that are passed into this function.
logicFile: (string)(required)(example: ‘/users/userslogic.php’) this is the php (can be any server side language that can interface with ajax) logic file path (I would use relative to the document root). So an example would be say your administrative panel logic file is separate from other areas of your website, say you have different logic files for different areas of your site. For small websites it’s not necessary to break sections up into logic files but when dealing with large and complex web apps, I like to break things up a bit for organizational and security purposes.
container: (string)(required if onComplete is null, otherwise you control the output container via the onComplete function – keep reading for details)(example: ‘.user_action_result’) this is the css element for the element container that will be populated with the processed and returned result/data from the logic file. Though it is required that this variable is assigned, it is not required for it to be a real element.
action: (string)(required) (example: ‘manage_users~add’) this is the action trigger which can take both a parent and sub action that are defined in the logic file (which will be further explained later). You will notice in the example there are two pieces delimited by a ~. The ~ indicates that there is a sub action to this action. in this example’s case we are triggering the action ‘manage_users’ and the of that action the sub action of ‘add’. so you can basically access different parts of the manage_users parent action by assigning a sub action. Note: it is not required that the action have a sub action. the sub action (‘~add’ in this case) is optional.
id: (string)(optional)(example: ’7′) This is an optional variable used in situations where you are trying to manipulate a specific record that is uniquely identified.
form: (string)(optional)(example: ‘username=jubairsaidi&email=bogus@bogus.com’) when working with forms of any size, this comes in very handy. don’t be fooled by the example, that is simple how it should look like being sent, however the way I work with this variable is by applying the .serialize() jQuery function on forms so I end up simply assigning a form to a variable (example: var serializedForm = $(‘.user_form’).serialize();) so all I have to do is in the form variable position within the proccessData function I just have the serializedForm variable sent.
onComplete: (function)(optional) (example: function(){ … } ) If you wish to do more than the default action for this function which is return the result to the specified element/container, such as take the returned data and run it through additional logic, then this is where you assign that function. it is possible to nest the processData function as many times as necessary for any given event trigger.
Now that the jQuery javascript function is covered, lets take a look at a php logic file example that the above function would interface with (note for simplicity’s sake, I chose to exclude the file security).
switch($_POST['action']) {
case 'manage_users':
switch($_POST['sub_action']){
case 'show_all':
echo('php logic pulling list of users from database and then echoes it here');
break;
case 'show_user':
echo('php logic pulling user information from database and then echoes it here');
break;
case 'add':
//add the logic here and then
if($user_added){
echo('User Added');
}else{
echo('User was not added. please try again.');
}
break;
case 'edit':
//add the logic here and then
if($user_edited){
echo('User Edited');
}else{
echo('User was not edited. please try again.');
}
break;
case 'delete':
//add the logic here and then
if($user_deleted){
echo('User Deleted');
}else{
echo('User was not deleted. please try again.');
}
break;
}
break;
case 'manage_comments':
...
break;
}
You get the idea.
now for event trigger usage. say you have a manage_users.php file that holds the interface that you use to manage your users. at the top of this file (or bottom, or included as a js file, however you choose) you should have the following.
$(document).ready(function(){
$('a.add_user').live('click',function(){
var addUserForm = $('form#add_user_form').serialize();
processData('/users/userslogic.php', '.add_user_result', 'manage_users~add', null, addUserForm, null);
});
});
So basically when ever any link with the class ‘.add_user’ is clicked, this above block is processed. now note that I used the .live event handler in this case. I did this because often I have action links/buttons within ajax loaded content and .click() only works on content that was loaded into the dom on page load (which ajax is post page load).
I hope this was helpful! if more you need more detail/examples/explanation, please feel free to contact me with any questions you may have.