phpBB

Development Wiki

Difference between revisions of "Using AJAX"

From phpBB Development Wiki

(TODO)
Line 58: Line 58:
 
* Error handling
 
* Error handling
 
* Advanced usage (calling ajaxify manually)
 
* Advanced usage (calling ajaxify manually)
 +
* Special server params like S_CONFIRM_ACTION, MESSAGE_TITLE, MESSAGE_TEXT, REFRESH_DATA, S_HIDDEN_FIELDS.

Revision as of 21:02, 12 February 2012

phpBB contains a set of functions to make it very easy to have links use AJAX. This means doing requests in JavaScript without reloading the whole page.

Supported elements

By default following elements can get ajaxified:

  • Links (<a>)
  • Forms (<form>)

Simple usage

To do so, simply add a
data-ajax="true"
attribute to the element. Here's an example:
<a href="/link.php?id=4" data-ajax="true">link</a>

This will make an AJAX call when the user clicks the link, instead of opening that page in the current browser tab.

Optionally you can add the
data-refresh="true"
attribute, which will refresh the page after the action is complete. While this can be useful, you should try to use ajax events whenever possible.

Ajax events

In most cases you will want to do something after the action is complete. You can do this by setting the
data-ajax
attribute to the event name you want to use. This will be a combination of your MOD name and the action that is happening.
<a href="/link.php?id=4" data-ajax="mymod.link_remove">link</a>

This will allow you to bind to your custom ajax event by adding a callback:

    phpbb.add_ajax_callback('mymod.link_remove', function() {
        $(this).remove();
    });
Once the AJAX response comes back, the callback is executed. In this case it will simply remove the link that was clicked on. As you can see,
this
is bound to the ajaxified element.

Accessing the response

If the server responds with JSON, you can use that data in your callback. The decoded data gets passed as the single argument to your callback. So you could do something like this:

    phpbb.add_ajax_callback('mymod.link_remove', function(data) {
        $(this).text(data.NEW_TEXT);
    });
This will take the
NEW_TEXT
variable from the response and set the text of the element to that value.

On the server side you need to check if the current request is an AJAX request. If it is, you should return JSON instead of a rendered page. You can send any data you need on the client. Here is an example:

    if ($request->is_ajax())
    {
        $new_text = $user->lang($activated ? 'ACTIVATE' : 'DEACTIVATE');
        $data = array('NEW_TEXT' => $new_text);
        phpbb_json_response::send($data);
    }
    
    // render normal response here

TODO

  • Forms
  • Error handling
  • Advanced usage (calling ajaxify manually)
  • Special server params like S_CONFIRM_ACTION, MESSAGE_TITLE, MESSAGE_TEXT, REFRESH_DATA, S_HIDDEN_FIELDS.