SugarCRM 7 - Making Ajax Requests

Sat 09 August 2014

jslogo

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({
    minLength: 2,
    source: function(request, response) {
        $.ajax({
            beforeSend: function (request)
            {
                request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());
            },
            url: "rest/v10/Accounts/filter",
            data: { "filter[0][name][$starts]": $('#your-input-box').val(), "fields":"id,name", max_num: 5},
            dataType: "json",
            type: "GET",
            success: function(data){
                response($.map(data.records, function(obj) {
                    return {
                        label: obj.name,
                        value: obj.name,
                        id: obj.id
                    };
                }));
            }
        });
    },
    select: function (event, ui) {
        $('#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({
            beforeSend: function (request)
            {
                request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());
            },
            url: "rest/v10/<YourModule>/<yourCustomAPIFn>",
            data: { arg1: arg1, arg2: arg2, arg3: arg3},
            dataType: "json",
            type: "POST",
            success: function(data){
                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/<YourModule>/<yourCustomApiFn.php>

if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('custom/modules/<YourModule>/<CustomClass>.php');
class yourCustomApiFn extends SugarApi
{
    public function registerApiRest()
    {
        return array(
            //GET
            'customAPIFn' => array(
                //request type
                'reqType' => 'POST',
                //endpoint path
                'path' => array('<YourModule>', '<yourCustomApiFn>'),
                //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);
    }

}

Category: SugarCRM Tagged: javascript jquery sugarcrm

Comments