Store
Community Documentation

v3 Knowledgebase

Updating a block with AJAX

From my observations, the phpfox AJAX system works by letting the client communicate with the module/mymodule/include/component/ajax/ajax.class.php file.
So to write some code to update a block, you need a few things.
1. Some code in the template to call the js function and get things started.
2. A function within the ajax.class.php that you will call.
3. The block.class.php and block.html.php files that you originally called and will replace upon invoking the AJAX call.
4. Any support file that you will need to use within the ajax file. In the case of this sample, it will be a service file.

As an example, I will use a block for RSVP that I made.

In this block, I have fields to allow the member to select how many people will be attending an event. I will want to return the parameters for the user's id and the number of attendees. In this case, both are in selection lists, so I will let js get the values of these elements. The actual call will start with the ajaxCall function:

$.ajaxCall('mymodule.getRSVP', 'id=' + $('#id').val() + '&NumReunion=' + $('#NumReunion').val());

The mymodule identifies which module's ajax file to target and getRSVP will be the function within that file to call. It is not calling the block directly!
The
'id=' + $('#id').val()
+
'&NumReunion=' + $('#NumReunion').val()
show that we are passing two parameters.

The final "return false;" will keep the screen from jumping around when we click the link.
The whole division looks like this:

HTML:
<div>
	<a href="#" onclick="$.ajaxCall('mymodule.getRSVP', 'id=' + $('#id').val() + '&NumReunion=' + $('#NumReunion').val());return false;" title="RSVP">{phrase var='mymodule.submit_your_rsvp'}</a>
</div>


In the ajax file, I want to do several things.
  • Primarily, I want to change the database to reflect the new information that the member is sending. I will do this by calling a service function to update the table.
  • Next, if the update is successful, I want to tell the member this. Likewise, if not successful, the member should know this as well. The messages will appear for 5 seconds and then fade out.
  • Last, I want to update the block so that the new totals for number attending will reflect the entry that the member just made.


Below is the commented code for the ajax function.

Since it will not display correctly here, I have put the code on github. The link is:
https://github.com/phpFox-webwolf/phpFox-Webcode/blob/master/KBAJAXblockUpdate

This code has worked for me. I hope it will help you create an awesome block for your site.