karkraeg
karkraeg

Reputation: 465

Use a trigger to evaluate xQuery and use return inside HTML page in eXistDB

I’d like to use a Button/link/whatever to call a xQuery function from my eXist Webapp and use the returned value to display a Bootstrap alert. So include a

<button type="button" class="btn btn-danger btn-circle">execute xQuery</button>

inside my html and if it’s clicked evaluate

let $name := "Peter"
return <div class="alert alert-success" role="alert">Hi {$name}</div>

(actually I want something more complex than this, but you get the idea..)

and return

<div class="alert alert-success" role="alert">Hi Peter</div>

inside my Page. Is this possible and if, how?

Using the Templating System does not help me here and just linking to an xQuery in my Database executes the query but redirects to another page showing the result. Can I use AJAX to evaluate the xQuery and modify the current DOM?

Thanks!

Upvotes: 0

Views: 208

Answers (1)

karkraeg
karkraeg

Reputation: 465

For reasons of completeness and future reference I will post a MWE of this here:

  1. Add a Button and a result panel to a page in eXist:
<a class="btn btn-danger run" id="path/to/the/xquery/in_your_app.xq" href="#">
   <i class="glyphicon glyphicon-play" /> Run xQuery
</a>
<img class="load-indicator" src="resources/img/ajax-loader.gif" />
<div style="margin-top: 12pt;" class="output" />
  1. Have a runxquery.js in your apps’ resources folder and reference it in your page.html:
$(document).ready(function() {
    $(".run").click(function(ev) {
        ev.preventDefault();
        file = this.id;
        var output = $(this).parent().parent().find(".output");
        var indicator = $(this).parent().parent().find(".load-indicator");
        function run() {
            indicator.show();
            output.hide();
            $.ajax({
                url: "/exist/rest/db/apps/yourapp/" + file,
                type: "GET",
                success: function(result) {
                    indicator.hide();
                    output.html(result);
                    output.slideDown(600);
                }
            });
        }

        if (output.is(":empty")) {
            run();
        } else {
            output.slideUp(800, function() {
                output.empty();
                run();
            });
        }
    });
});
  1. Clicking the Button will trigger the xquery defined in the id of the button inside your apps folder.

  2. If running the xQuery should return HTML Code, you need to specify this in the xQuery:

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "html";
declare option output:media-type "application/html";

let $text := "This is the alert text"

return 
<div class="alert alert-success alert-dismissible" data-dismiss="alert" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"/>
   {$text}
</div>

Upvotes: 1

Related Questions