$id = isset($get['id']) ? $get['id'] : null;
$rs = $core->blog->getPost(array('post_id' => $id));
$date = strtotime($rs->post_dt);
# Time difference (in seconds) between now and the publication date
$delta = $date - time();
Now we have the information we need, it is possible to manipulate it to use the format we want. We can for instance pass the format we want as a parameter in the URL and convert the
# Creation of the wrapper
$rsp = new xmlTag();
# Add the "value" node in the "rsp" node containing the $delta variable
$rsp->value($delta);
# Return everything
return $rsp;
The generated XML file will look like this:
65765432456
$core->rest->addFunction('getPostRemainingTime',array('myPluginRestMethods','getPostRemainingTime'));
This code has to be put in the plugin [[files#general-organization-of-a-plugin|_prepend.php]] file. Now our service is declared, we can access it throught the **//ADMIN_URL/services.php?f=getPostRemainingTime&id=1//** URL. Check if it works correctly before going further.
$(function(){
$('#remaining-time').click(function(){
$.get('services.php',
{f: 'getPostRemainingTime',id: $('#id').val()},
function(rsp){
$('#remaining-time-display').html('Remaining time before online publishing:'+$(rsp).find('value').text()+'
');
});
});
});
When clicking on the element with ID **remaining-time**, a request is made to the **getPostRemainingTime** service, passing the service we want to use and the current post ID (retrieved using the hidden **id** field of the form) as parameters. The response is displayed in the block with ID **remaining-time-display**.
===== Error handling =====
The code above does not handle errors that may happen when requesting the service. The advantage of using the //xmlTags// class to generate the XML is that if an exception is raised, the returned XML will look like:
Exception message
For instance, for our service, if no ID is passed in parameter, we will raise an exception to inform the user:
$id = isset($_GET['id']) ? $_GET['id'] : null;
if ($id === null) {
throw new Exception(__('No ID given'));
}
It is therefore very easy to catch this kind of XML to handle it differently. For instance:
$(function(){
$('#remaining-time').click(function(){
$.get('services.php',
{f: 'getPostRemainingTime',id: $('#id').val()},
function(data){
var rsp = $(data).children('rsp')[0];
if (rsp.attributes[0].value == 'ok') {
$('#remaining-time-display').html('Remaining time before online publishing:'+$(rsp).find('value').text()+'
');
} else {
alert($(rsp).find('message').text());
}
});
});
});
This code will inform the user through an //alert()// message that an error appeared when requesting the service, or during the service processing.