kvikende's blog


Archive for August, 2012

Login to SugarCRM with its REST API from Javascript

Monday, August 20th, 2012

Hello. I’ve been doing a summer project where I’ve developed a mobile-friendly website for SugarCRM. Only catch was that the site had to call the SugarCRM’s REST api from Javascript rather than from PHP. All examples on the web was with PHP, so I figured I should write some quick posts with Javascript examples. All code is under the MIT licence. Do as you please.

Please note that I’m using jQuery.

First example is login.

/* First get the username and password from the login fields. */
var username = $('#UsernameField').val();
var password = $('#PasswordField').val();

/* Then hash the password with md5 */
var hashedPassword = $.md5(password);

/* Prepare the "header", if you like, specifying which REST API method
 * is to be called and that we're about to use JSON.
 */
var dataToSend = {
	method : "login",
	input_type : "JSON",
	response_type : "JSON"
};

/* Prepare an object which is going to be converted into
 * JSON. You don't want to write JSON manually.
 */
var restData = {
	user_auth : {
		user_name : username,
		password : hashedPassword
	},
	application : "SugarCRM",
	name_value_list : {
		name : "language",
		value : "en_US"
	}
};
/* Convert the object to JSON with the browser's
 * built in JSON.stringify() command.
 */
dataToSend.rest_data = JSON.stringify(restData);

/* UrlToRestApi is the URL to the rest.php file somewhere in the SugarCRM instance. */
$.post(UrlToRestApi, dataToSend,
	function(data) {
		/* This is the callback method which will be run when
		 * the server responds.
		 */
		var response = $.parseJSON(data);
		/* Logical AND here. Blog is being stupid. */
		if (response.name !== undefined && response.name === "Invalid Login") {
			alert("Username and/or password is invalid.");
			return;
		}
		/* Here the login did not fail. Store the session ID sugar gives us.
		 * It will be important later.
		 */
		SugarSessionId = response.id;
	});

Please note that I’m aware that SugarCRM is “OpenCore”.