Summary: Serve a page by JSON (presumably for AJAX)
Version: 2013-05-02
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?


Serve pages by JSON for use in AJAX.


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(


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="" />
<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");
  url: url,
}).done(function( json ) {
  if (json['title'])
    $("#helpscreen").dialog({ title: json['title'] });
  if (json['body'])
    $('#helpscreen').html('<i>No help content for this page.</i>');
  $("#helpscreen").dialog({width: "auto", height: "auto", position: {my:"center", at:"center", of:window} });


Appreciation to Petko for his help in getting this working.

Change log / Release notes

  • 2013-05-02 Initial Release

See also



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.