Recent Changes - Search:

Cookbook

PmWiki

pmwiki.org

ServePageByJSON

Summary: Serve a page by JSON (presumably for AJAX)
Version: 2013-05-02
Prerequisites:
Status: Working
Maintainer: Peter Bowers
Categories: Ajax
Users: (view? / edit)

Questions answered by this recipe

  • I wish to access page text from a separate script via AJAX. How can I get the HTML to be sent via JSON?

Description

Serve pages by JSON for use in AJAX.

Installation

In config.php

$HandleActions['json'] = 'HandleServeJSON';
$HandleAuth['json'] = 'read';
function HandleServeJSON($pagename, $auth = 'read')
{
    global $HandleBrowseFmt;
    $HandleBrowseFmt = array('function:PrintJSON');
    HandleBrowse($pagename, $auth);
}

function PrintJSON($pagename)
{
    global $FmtV;
    header("Content-type: application/json");
    print json_encode(array(
            'title'=>PageVar($pagename,'$Titlespaced'),
            'body'=>$FmtV['$PageText'],
          ));
}

Usage

Obviously your AJAX call may vary greatly depending on your application, but here is one example putting the contents of the page in a jquery-ui dialog with ID=helpscreen:

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.2/ui/minified/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css" />
...
<div id="helpscreen" style="display:none"></div>
...
<script type="text/javascript">
...
url = 'pmwiki/pmwiki.php?n=Mygroup.Mypage&action=json';
$("#helpscreen").html("<i>Loading content...</i>").dialog({ title: title }).dialog("open");
$.ajax({
  url: url,
}).done(function( json ) {
  if (json['title'])
    $("#helpscreen").dialog({ title: json['title'] });
  if (json['body'])
    $('#helpscreen').html(json['body']);
  else
    $('#helpscreen').html('<i>No help content for this page.</i>');
  $("#helpscreen").dialog({width: "auto", height: "auto", position: {my:"center", at:"center", of:window} });
});
</script>

Notes

Appreciation to Petko for his help in getting this working.

Change log / Release notes

  • 2013-05-02 Initial Release

See also

Contributors

Comments

See discussion at ServePageByJSON-Talk?

User notes? : If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.

Edit - History - Print - Recent Changes - Search
Page last modified on May 02, 2013, at 06:17 AM