Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Monday, June 13, 2016

Calling RESTful API in Javascript


Here, we will call the RESTful API from javascript.

Suppose there is a RESTful API which URL is: http://localhost:8083/saveEmployeeDetail

And I want to save employee information using Javascript.

We will call the above API using “POST” method.

There is a button in html page which. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here I am using “XMLHttpRequest” to call RESTful API.



1.  Testing.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <title></title>
</head>
<body ng-controller='loaderCtrl'>
    <input type="button" value="Submit" onclick="saveDetails()" />
    <script src="testing.js"></script>
</body>
</html>

2.  testing.js
var sendRequest = function (config, method) {
    if (!config) return;

    var ajaxHandler = new Object();

    if (window.XMLHttpRequest) {
        ajaxHandler.ajaxReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        ajaxHandler.ajaxReq = new ActiveXObject('Microsoft.XMLHTTP');
    }

    ajaxHandler.ajaxResponse = function () {
        // Only if req shows "complete"
        var readyState, status;
        readyState = ajaxHandler.ajaxReq.readyState;
        if (readyState == 4) {
            status = ajaxHandler.ajaxReq.status;
        }
        if (readyState == 4) {
            if (status == 200) {
                document.writeln(ajaxHandler.ajaxReq.responseText);// here response will come success                 
                 
            } else {
                document.writeln(ajaxHandler.ajaxReq.responseText);// here response will come  show failed message                

            }
        }
    }
    ajaxHandler.ajaxReq.onreadystatechange = ajaxHandler.ajaxResponse;
    ajaxHandler.ajaxReq.open(method, "http://localhost:8083/saveEmployeeDetail", true); // second parameter is the URl of the REST API
    ajaxHandler.ajaxReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    //ajaxHandler.ajaxReq.headers = { "Authorization": "Basic " + btoa("admin:admin") };               
    ajaxHandler.ajaxReq.send(JSON.stringify(config));
}

function saveDetails() {
    var config = {
        "empID": 1001,
        "firstName": "Shshi Bhooshan",
    };

    sendRequest(config, "POST");
}



Hope this is helpful example for you. Leave your comment and provide your suggestion if any.