Thursday, May 23, 2013

Simple html page with JQuery to call an API

I had been developing an API using EJB and some of the interns (they are supposed to develop the client application) had a problem in understanding how to communicate with the API. When I asked them to initiate POST request to an API using javascript only, they looked puzzled.

Thus, I thought to share a sample code with you.

Important code segments to take note.
jQuery.support.cors = true: Force cross site scripting (XSS). Importantly, to work in internet explorer
jQuery.parseJSON(result): A well-formed JSON string is turned to a javascript object.

index.html page is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>Sample jQuery Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

Login = function() {

 var resultDiv = $("#resultDiv");
 jQuery.support.cors = true;    //force cross site scripting - XSS
$.ajax({
        url: "http://xyz.abc.com/user/login",
        type: "POST",
        data: { username: $("#username").val(), password: $("#password").val(), callback: "?" },
        dataType: "text",
        success: function (result) {
            alert(result);
            var res = jQuery.parseJSON(result);
            var status= res.status;
            alert(status);
            switch (status) {
                case 0:
                   alert("sessionId: " + res.sessionId);
                   alert("My profileId: "+ res.profileId);
                   resultDiv.html(result);
                   break;
                default: //e.g. at invalide username, status=2
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>Sample jQuery Web Page - Login</h1>

<form>
<label>Username</label>
<input name="Username" type="text" id="username"  /> <br/><br/>
<label>Password</label>
<input name="Password" type="password" id = "password" />
<input name="Submit" type="button" id="submit" onclick="Login()" value="Submit" />
</form>


<div id="resultDiv"></div>


</body>
</html

No comments:

Post a Comment