Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Having a hard time updating right Confluence page with Ajax jQuery

Daniel Baron March 13, 2018

I've embedded the following javascript in an HTML macro in an attempt to automatically update one or more Confluence pages upon the submission of a form. The code can successfully Get the body of the page(s) that I want to update, but something seems to be going wrong in the $.ajax section when making a PUT request with the updated body back to the target url. I'm currently not getting a "Success!!!" alert and the page isn't getting updated. I'm using Confluence Server. Does anyone have some insight?

<script>src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"</script>
<script>
function makeJSON(){
  var users_name = document.getElementById("users_name").value;
  var email = document.getElementById("email").value;
  inputs = document.getElementsByTagName('select');
    for (i=0; i<inputs.length; i++) {
      input = inputs[i];
      if (input.value >= 1 && input.value <= 5) {    
        var skillString = " " + users_name + " (" + input.value + ") - " + email 
        var skillName = input.name

        $.get('/rest/api/content?spaceKey=EXPERTISE&title='+ skillName + '&expand=space,body.view,version,container', function(data, status){
 		  var response = JSON.stringify(data);
		  var parsedData = JSON.parse(response);
		  // Not having a var in front of page_id, page_body, version, etc makes these variables global
          page_id = parsedData.results[0].id;
		  page_body = parsedData.results[0].body.view.value
		  version = parsedData.results[0].version.number
        });		
		
        page_body += skillString;
	$.ajax({
    	  type: "PUT",  
          url: "/rest/api/content/" + page_id,	
    	  data: JSON.stringify(skillString),    
		  contentType:"application/json; charset=utf-8",
		  success: function (data) {
			$("p").prepend(JSON.stringify(page_body));
        	        alert("Success!!!")
    	  }
	});
      } 
    }
}
</script>
<form onSubmit="makeJSON()" action="/rest/api/content" method="PUT">

 

1 answer

1 vote
Stephen Deutsch
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
March 14, 2018

First of all, I would recommend not loading another version of jQuery, as Confluence should already have a version running (it is an older version, like 1.7.2 and might be accessible under AJS.$, but probably also as $).

Second, I'm not sure why you're using JSON.stringify and JSON.parse right after one another. After doing both of those commands, data should be exactly the same as parsedData anyways.

Finally, when you update a page, you need to increment the version number by one, or else the API will throw an error.  You should be able to see the error message in the Network tab of your browser console, and that should help you figure out the error.

Daniel Baron March 14, 2018

Thanks for the tips. I've included an incrementation for the version and included it in the Put request as shown below, however I'm getting a 'failed to load resource 400 (Bad request)' error. Is this an issue with an incorrect structure for version?  

function makeJSON(){
  var users_name = document.getElementById("users_name").value;
  var email = document.getElementById("email").value;
  inputs = document.getElementsByTagName('select');
    for (i=0; i<inputs.length; i++) {
      input = inputs[i];
      if (input.value >= 1 && input.value <= 5) {    
        var skillString = " " + users_name + " (" + input.value + ") - " + email 
        var skillName = input.name

        $.get('/rest/api/content?spaceKey=EXPERTISE&title='+ skillName + '&expand=space,body.view,version,container', function(data, status){
          page_id = data.results[0].id;
    page_body = data.results[0].body.view.value
    version = data.results[0].version.number
        });  

var new_version = version + 1;
$.ajax({ type: "PUT", url: "/rest/api/content/" + page_id, data: JSON.stringify(skillString), contentType:"application/json; charset=utf-8", version:{"number":new_version},
body:{"storage": {
"value": skillString,
"representation": "storage",
}
}, success: function (data) { $("p").prepend(JSON.stringify(page_body)); alert("Success!") } }); } } }

Error string from the browser Network tab:

VM18197:1 PUT https://wiki.zymergen.net/rest/api/content/8002885 400 (Bad Request)
(anonymous) @ VM18197:1

XMLHttpRequest.send @ batch.js?nps-not-opted-out=true&analytics-uploadable=true&nps-acknowledged=true&analytics-enabled=true&locale=en-GB&anonymous-access-enabled=true&is-server-instance=true&nps-enabled=true&hostenabled=true:565

send @ batch.js?atlassian.aui.raphael.disabled=true&locale=en-GB:506

ajax @ batch.js?atlassian.aui.raphael.disabled=true&locale=en-GB:500

makeJSON @ viewpagetemplate.action?entityId=9469968&key=EXPERTISE:578

onclick @ viewpagetemplate.action?entityId=9469968&key=EXPERTISE:708

Stephen Deutsch
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
March 15, 2018

I had to guess a little bit at what you're trying to accomplish, but this is probably in the right direction:

function makeJSON() {
var users_name = document.getElementById("users_name").value;
var email = document.getElementById("email").value;
inputs = document.getElementsByTagName('select');
for (i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.value >= 1 && input.value <= 5) {
var skillString = "<p> " + users_name + " (" + input.value + ") - " + email + '</p>';
var skillName = input.name;

$.get('/rest/api/content?spaceKey=EXPERTISE&title=' + skillName + '&expand=space,body.storage,version,container', function (data, status) {
var pageData = data.results[0];
var page_id = pageData.id;
pageData.body.storage.value = skillString + pageData.body.storage.value;
pageData.version.number += 1;

$.ajax({
type: "PUT",
url: "/rest/api/content/" + page_id,
data: JSON.stringify(pageData),
contentType: "application/json; charset=utf-8",
success: function (data) {
$("p").prepend(skillString);
alert("Success!");
},
error: function (data) {
console.log(data);
}
});
});
}
}
}
Daniel Baron March 15, 2018

You're right, I had it wrong by not nesting the put call inside the get. But the strange thing is that the put request is not only updating the target url page of

"/rest/api/content/" + page_id

with the skillString but is also adding the skillSet string to the actual form itself. I can avoid the problem by making the prepend to something more specific to the target page for updates than a paragraph tag but I'm confused about why the form itself is getting modified. 

Stephen Deutsch
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
March 16, 2018

Well, $("p") selects all p tags in the page, and there are a ton of p tags in every Confluence page (you can see some examples by clicking "View Storage Format" in the ••• menu). It's likely that Confluence fills in extra p tags to separate elements of your form.

Daniel Baron March 16, 2018

That's true about the p tags, but it's not just the p tags on the specified url page getting updated. Submitting the form also causes the skillString to be added to the form page itself (the target page specified by the url is correctly being updated with the skillString).  See the images below for the form page before and after clicking submit.

image.png

 

-------------------

And after submitting the form, note Tess Ting (3) - test@gmail.com being added to each p tag in the form page.

-------------------

 

image.png

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events