Thursday, November 15, 2018

jQuery AJAX calls to a RESTlet from within a Suitelet

It is possible to create interactive Suitelets using inline HTML content and the jQuery library. In addition, AJAX calls can be made from within Suitelets using jQuery's ajax() function, enabling for the development of highly-dynamic, JSON-driven Suitelets within NetSuite.

To create this interaction, the jQuery code needs to be placed inside a Client script and attached to the Page Init event. This client script can then be used in a Suitelet by using the setScript() function.

The following code demonstrates this concept:

*** INLINE HTML CONTENT ***
// Upload this file to your File Cabinet and take note of the internal ID.<p id="inline_p1">	paragraph 1</p>
*** END OF INLINE HTML CONTENT ***
*** CLIENT SCRIPT ***
function pageInit(){	$('#custpage_button').click(function(e) {		var url = "/app/site/hosting/restlet.nl?script=380&deploy=1";		$.ajax({			url: url,			beforeSend: function(jqXHR, settings) {				jqXHR.setRequestHeader("Content-type", "application/json");			}		}).done(function(data) {			$("#inline_p1").text(data.text);		});	});}
*** END OF CLIENT SCRIPT
*** SUITELET ***
var form = nlapiCreateForm('AJAX Suitelet Form');var btn = form.addButton('custpage_button', 'PUSH ME!');var fld1 = form.addField('custpage_inline', 'inlinehtml');	// The 'fileId' is the internal ID of the HTML file in your File Cabinet.var file = nlapiLoadFile(fileId);var contents = file.getValue();fld1.setDefaultValue(contents);	// You then need to set the Client script to the Suitelet.form.setScript('customscript_client');response.writePage(form);
*** END OF SUITELET ***

This works because of the following points:

  • The 'inlinehtml' field is always rendered as an element. This enables us to access the HTML content directly using jQuery.
  • Client scripts can call the RESTlet directly without having to bother with any cross-domain restrictions.

    No comments:

    Post a Comment