Skip to content

Instantly share code, notes, and snippets.

@amusarra
Created April 7, 2014 12:05
Show Gist options
  • Save amusarra/10019059 to your computer and use it in GitHub Desktop.
Save amusarra/10019059 to your computer and use it in GitHub Desktop.
SugarCRM REST API - Authentication via JQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SugarCRM Login via REST API</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<header>
<h1>SugarCRM REST API</h1>
</header>
<section>
<article>
<h2>SugarCRM Login via REST API</h2>
<form action="http://sugarcrmpgsql-shiruslabs.rhcloud.com/service/v4_1/rest.php" method="post" id="sugarcrmLoginForm">
<label>Username:
<input id="username" placeholder="SugarCRM UserName" autofocus required>
</label>
<label>Password
<input id="password" placeholder="SugarCRM Password" autofocus required>
</label>
<input type="reset" value="Reset">
<input type="submit" value="Login">
</form>
<div id="loginResult">
</div>
</article>
</section>
<script>
//hang on event of form with id=myform
$("#sugarcrmLoginForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
// prepare a data for submit
var loginParams = {
user_auth:{
user_name:$("#username").val(),
password:$("#password").val(),
encryption:"PLAIN"
},
application: "SugarCRM REST API"
};
var dataToPost = {
method: "login",
input_type: "JSON",
response_type: "JSON",
rest_data: JSON.stringify(loginParams)
};
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'json',
data: dataToPost,
success: function(result) {
if(result.id) {
$("#loginResult").text("Sucessfully login. Your session ID is : " + result.id).show();
} else {
$("#loginResult").text("Error on login: "
+ result.name
+ " - "
+ result.number
+ " - "
+ result.description).show();
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#loginResult").text("Errors occurred during the call to service.").show();
}
});
return false;
});
</script>
</body>
</html>
@selloutdesign
Copy link

I love this! Thanks.

Also mention somewhere that CORS needs to be enabled on the server that is being requested. That stumped me for a minute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment