SugarCRM 7 — Making Ajax Requests

Posted on Sat 09 August 2014 in Tech

SugarCRM has a pretty great API if you know how to poll it. Today I'm sharing two examples of where I've needed to poll SugarCRM's API with some sample jQuery code.

A jQuery autocompleter

If you're declaring an input box and wish to autocomplete it's results based on the results from a particular module, this sample code should get you started.

$( "#your-input-box").autocomplete({
 $.ajax({
 {
   request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());
 },
 response($.map(data.records, function(obj) {
   return {
   };
   }));
   }
   });
   },
   $('#your-input-box').val(ui.item.label);
   $('#your-input-box-id').val(ui.item.id);
 return false;
 }
 });

Note: This leverages the existing SugarCRM API to populate this data. You can customise the filter however you want, just load up firebug/a web inspector and do a few sample requests from Sugar's core fieldset if you need sample requests to work with.

This is really useful for leveraging existing endpoints, but what if you want to have Javascript call a custom piece of code you've written?

Call a custom API Endpoint via a jQuery ajax request.

Here's a sample piece of Javascript that will grab some input fields and create your post request.

$('#some-button').click(function() {
 var arg1 = $('#field1').val();
 var arg2 = $('#field2').val();
 var arg3 = $('#field3').val();

$.ajax({
 {
 request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());
 },
 alert(data);
 window.location.reload();
 }
 });
 });

And here is the API code that would handle a post request with multiple arguments.

This would be placed in custom/modules//

if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
 require_once('custom/modules//.php');
 class yourCustomApiFn extends SugarApi
 {
 public function registerApiRest()
 {
 return array(
 //GET
 'customAPIFn' => array(
 //request type
 'reqType' => 'POST',
 //endpoint path
 'path' => array('', ''),
 //endpoint variables
 'pathVars' => array('module', 'action'),
 //method to call
 'method' => 'doSomething',
 //short help string to be displayed in the help documentation
 'shortHelp' => 'Does something really useful',
 ),
 );
 }

/**
 * Method to be used for my MyEndpoint/GetExample endpoint
 */
 public function doSomething($api, $args)
 {
 $arg1 = $args['arg1'];
 $arg2 = $args['arg2'];
 $arg3 = $args['arg3'];

$custom_bean = new CustomClass();
 return $custom_bean->doSomething($arg1, $arg2, $arg3);
 }

}