Tuesday, 30 April 2013

SugarCRM REST API example with javascript

Greetings!

This blog post explains how to login to SugarCRM instance through javascript

Let's have an example of REST API through JavaScript.


Create an html file to include javascript, We will require jquery. Provide correct Javascript path in HTML file
<ANYNAME>.html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>SugaRCRM REST API Example through Javascript</title>
        <script src='jquery.js'></script>
        <script src='rest.js'></script>
     </head>
</script>
    </head>
    <body >
        <div class="hd">SugaRCRM REST API Example through Javascript</div>
    </body>
</html>



Now create a rest.js


var api_url = "<SUGAR_URL>/service/v2/rest.php";
var user_name = '<USERNAME>';    //SugarCRM username
var password = '<PASSWORD>';    //SugarCRM password

var params = {
    user_auth:{
        user_name:user_name,
        password:password,
        encryption:'PLAIN'
    },
    application: 'SugarCRM RestAPI Example'
};
var json = JSON.stringify(params);
$.ajax({
        url: api_url,
        type: "POST",
        data: { method: "login", input_type: "JSON", response_type: "JSON", rest_data: json },
        dataType: "json",
        success: function(result) {
             if(result.id) {
                    //HERE: you will have out put from rest
                alert("sucessfully LOGIN Your session ID is : " + result.id);
             }
             else
                 alert("Error");
              
        },
        error: function(result) {
           alert("Error");
        }
});


On success you will get response of login method, successful or failure.

5 comments:

  1. i keep getting Unexpected token error, even though i successfully receive JSON back. ANy ideas?

    ReplyDelete
    Replies
    1. Hello Marcus

      Can you send me your example files? and what Sugar version and flavor you are using ?

      Delete
  2. Hi,
    I tried this like i have taken 1 html and 1 rest.js file and run html file but i didn't get any result please tell me.

    ReplyDelete
    Replies
    1. Please email us your files and we check and point your errors.

      Delete
  3. It fails for me :(

    Is there anyway I can find out where it is going wrong?

    ReplyDelete

Urdhva Tech Pvt. Ltd. Powered by Blogger.

Urdhva Tech

My Photo
SugarCRM Consultants Contact us at contact@urdhva-tech.com Skype : urdhvatech

Search This Blog

Loading...

Stay connected Socially

     

Total Pageviews

Popular Posts