Shane Dowling : SugarCRM 7 — Making Ajax Requests

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({
   request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());
 response($.map(data.records, function(obj) {
   return {
 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();

 request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());

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');
 class yourCustomApiFn extends SugarApi
 public function registerApiRest()
 return array(
 '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);