(ScriptRunner) Closing a diaglog2 box after sending data

I am trying to create a Confluence page from Jira.

I am very new to HTML and Javascript. And Atlassian’s AUI documentation isn’t the best, and I cant really find any documentation on AJS. So I’m really struggling with this.

  1. I am using a ScriptRunner Web Item Fragment, which shows a button on a Jira issue.
  2. Once this button is clicked I have a custom ScriptRunner REST Endpoint which opens a dialog box (called createConfluencePageDialog) where the user can enter the page title and page body of the Confluence page they want created. This is using the AUI Diaglog2 and AUI Forms.
  3. There is a button on the Form called “Submit” which sends the data in the form to another custom ScriptRunner REST Endpoint (called createConfluencePage) which creates the Confluence Page.

The issue I am facing is, the Form on createConfluencePageDialog has an “action” tag which sends the data to createConfluencePage, however, it also redirects to whatever is returned by createConfluencePage. If createConfluencePage doesn’t return anything, then nothing happens i.e. the dialogue ox just stays open.

But what I want to happen is once “Submit” is clicked on the createConfluencePageDiaglog diaglog box, the data in form to be sent AND to close the dialog box down.

What works:

  1. I can create a Confluence page from Jira

What I have tried - all Javascript I have used is in HTML under the tag:

  1. I have tried adding a Javascript that closes the diaglog box once the button is clicked, however, this just closes the diaglog box without it sending the data to createConfluencePage
@BaseScript CustomEndpointDelegate delegate

createConfluencePageDialog(httpMethod: "GET", groups: ["jira-servicedesk-users"]) { MultivaluedMap queryParams ->

// ... (Other stuff I am omitting as I don't think it's relevant - I can paste the full code of needed)

def dialog =
    """ 
	<section id="sr-dialog" class="aui-layer aui-dialog2 aui-dialog2-xlarge" role="dialog" aria-hidden="true"> 
		<header class="aui-dialog2-header">
			<h2 class="aui-dialog2-header-main">Create Confluence Page</h2>
			<a class="aui-dialog2-header-close"><span class="aui-icon aui-icon-small aui-iconfont-close-dialog">Close</span></a> 
		</header> 
		<div class="aui-dialog2-content"> 
			<form id="my-custom-sr-dialog-form" class="aui" action="/rest/scriptrunner/latest/custom/createConfluencePage"> 
				<div class="page-details">
					<p>Please enter the details for the Confluence page you want to create<br></p>
                    <label for="page-title">Page Title<span class="aui-icon icon-required">required</span></label>
					<input class="text full-width-field" name="pageTitle" id="page-title" type="text" maxlength="255"/>
                    <br><br>
                    <label for="page-body">Page Body<span class="aui-icon icon-required">required</span></label>
                    <textarea class="textarea full-width-field" name="pageBody" id="page-body" placeholder="Enter what will be contained in the page here... "></textarea>
                    <br><br>
				</div>
				<button id="submit-button" class="aui-button aui-button-primary" type="submit">Submit</button> 
			</form> 
            <script>
                AJS.\$("#submit-button").click(function (e) {
                    e.preventDefault();
                    AJS.dialog2("#sr-dialog").remove();
                });
            </script>
		</div> 
		<footer class="aui-dialog2-footer"> 
			<div class="aui-dialog2-footer-actions">
				<button id="dialog-close-button" class="aui-button aui-button-link">Close</button> 
			</div>
			<div class="aui-dialog2-footer-hint">Click "Close" on the right to close this window WITHOUT creating a Confluence page</div> 
		</footer> 
	</section>
	"""

    return javax.ws.rs.core.Response.ok().type(MediaType.TEXT_HTML).entity(dialog.toString()).build()
}
  1. I have tried removing the “action” field in the Form (so the Form doesn’t do anything on submit) and adding javascript on the “Submit” button click that sends the data in the form to createConfluencePage. However, this doesn’t work, I’m not sure why but it doesn’t run the createConfluencePage REST endpoint. I don’t really know how to output to the ScriptRunner log when it’s running Javascript in the tag in HTML.
@BaseScript CustomEndpointDelegate delegate

createConfluencePageDialog(httpMethod: "GET", groups: ["jira-servicedesk-users"]) { MultivaluedMap queryParams ->

// ... (Other stuff I am omitting as I don't think it's relevant - I can paste the full code of needed)

    def dialog =
    """ 
	<section id="sr-dialog" class="aui-layer aui-dialog2 aui-dialog2-xlarge" role="dialog" aria-hidden="true" data-aui-remove-on-hide="true"> 
		<header class="aui-dialog2-header">
			<h2 class="aui-dialog2-header-main">Create Confluence Page</h2>
			<a class="aui-dialog2-header-close"><span class="aui-icon aui-icon-small aui-iconfont-close-dialog">Close</span></a> 
		</header> 
		<div class="aui-dialog2-content"> 
			<form id="conf-page-form" class="aui"> 
				<div class="page-details">
					<p>Please enter the details for the Confluence page you want to create<br></p>
                    <label for="page-title">Page Title<span class="aui-icon icon-required">required</span></label>
					<input class="text full-width-field" name="pageTitle" id="page-title" type="text" maxlength="255"/>
                    <br><br>
                    <label for="page-body">Page Body<span class="aui-icon icon-required">required</span></label>
                    <textarea class="textarea full-width-field" name="pageBody" id="page-body" placeholder="Enter what will be contained in the page here... "></textarea>
                    <br><br>
				</div>
				<button id="submit-button" class="aui-button aui-button-primary">Submit</button> 
			</form>
            <button id="submit-button-test" class="aui-button">Submit Test</button>
            <script>
                AJS.dialog2.on("show", function (e) {
                    var targetId = e.target.id;
                    if (targetId === "sr-dialog") {
                        var someDialog = AJS.dialog2(e.target);
                        \$(e.target).find("#submit-button-test").click(function (button) {
                            \$.ajax({
                                type: "GET",
                                url: AJS.contextPath() + "/rest/scriptrunner/latest/custom/createConfluencePage",
                                data: AJS.\$(window.opener.document).find("#conf-page-form").serialize(),
                                beforeSend: function (request) {
                                    request.setRequestHeader("X-Atlassian-token", "no-check");
                                }
                            }).done(function(response) {
                                e.preventDefault();
                                someDialog.hide();
                            });
                        });
                    }
                });
            </script>
		</div> 
		<footer class="aui-dialog2-footer"> 
			<div class="aui-dialog2-footer-actions">
				<button id="dialog-close-button" class="aui-button aui-button-link">Close</button> 
			</div>
			<div class="aui-dialog2-footer-hint">Click "Close" on the right to close this window WITHOUT creating a Confluence page</div> 
		</footer> 
	</section>
	"""

    return javax.ws.rs.core.Response.ok().type(MediaType.TEXT_HTML).entity(dialog.toString()).build()
}
  1. I’ve even tried to be cheeky and use the redirect on the Form. In createConfluencePage I tried to return an HTML page that would simply redirect them back to the previous page using: tag. However, I couldn’t find any way to do this

Here is the code in createConfluencePage (I commented out the code regarding point 3 above).

import com.atlassian.applinks.api.ApplicationLink
import com.atlassian.applinks.api.ApplicationLinkRequest
import com.atlassian.applinks.api.ApplicationLinkService
import com.atlassian.applinks.api.application.confluence.ConfluenceApplicationType
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.sal.api.net.Request
import com.atlassian.sal.api.net.Response
import com.atlassian.sal.api.net.ResponseException
import com.atlassian.sal.api.net.ResponseHandler

import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.BaseScript

import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.MediaType

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate

@BaseScript CustomEndpointDelegate delegate

createConfluencePage(httpMethod: "GET", groups: ["jira-servicedesk-users"]) { MultivaluedMap queryParams ->
	log.debug("Logging is working")
    def issueManager = ComponentAccessor.getIssueManager()
    
    // set the page title - this should be unique in the space or page creation will fail
    def pageTitle = queryParams.getFirst("pageTitle") as String
    def pageBody = queryParams.getFirst("pageBody") as String
    
    log.warn("Page Title is below:")
    log.warn(pageTitle)
    
    log.warn("Page Body is below:")
    log.warn(pageBody)
    
    def params = [
        type : "page",
        title: pageTitle,
        space: [
            key: "ITSDT" // set the space key - or calculate it from the project or something
        ],
        // if you want to specify create the page under another, do it like this:
        ancestors: [
            [
                type: "page",
                id: "51281937", // Id of the page "IT Service Desk Test Home Page" on the "IT Service Desk Test" Space
            ]
        ],
        body : [
            storage: [
                value         : pageBody,
                representation: "wiki"
            ],
        ],
    ]
    
    def applicationLinkService = ComponentLocator.getComponent(ApplicationLinkService)
    final ApplicationLink conflLink = applicationLinkService.getPrimaryApplicationLink(ConfluenceApplicationType)
    
	assert conflLink // must have a working app link set up
    
    def applicationLinkRequestFactory = conflLink.createAuthenticatedRequestFactory()
    
    applicationLinkRequestFactory
    .createRequest(Request.MethodType.POST, "rest/api/content")
    .addHeader("Content-Type", "application/json")
    .setRequestBody(new JsonBuilder(params).toString())
    .execute(new ResponseHandler<Response>() {
        @Override
        void handle(Response response) throws ResponseException {
            if (response.statusCode != HttpURLConnection.HTTP_OK) {
                throw new Exception(response.getResponseBodyAsString())
            } else {
                def webUrl = new JsonSlurper().parseText(response.responseBodyAsString)["_links"]["webui"]
            }
        }
    })
    
    /*
    def retPage = 
    """
    <html>
      <body>
        <p>Please follow <a href="javascript:history.back()">this link</a> to go back.</p>
      </body>
    </html>
    """
    
    def retResp = javax.ws.rs.core.Response.ok().build()
    
    return retResp
    */
}