Friday, January 11, 2019

Add Basic Authentication to ajax request

In this post, I am going to explain how to pass the user credentials to a service that is enabled with basic authentication. In demo example, I have used the ajax jQuery request to connect to a service that validates user based on the credentials that we send in authentication header, if user successfully validated then it will return the data in JSON format and that data will get displayed on webpage in tabular format.

If you are interested in getting to know how to enable basic authentication in MVC application, you can refer my this blog.
Lets get started
Step 1 CDN for jQueryjQuery min 
Step 2 – HTML Code – in this example
<table id="tblProcess">
                    <tr>
                        <th>Process Id</th>
                        <th>File Name</th>
                        <th>Source Name</th>
                        <th>Process Time</th>
                        <th>Process Status</th>
                        <th>Email To</th>
                    </tr>
                </table>
Step 3 – Javascript code
        $(document).ready(function () {
            var userName = //Set the user Id;
            var password = //Set the password;
            $.ajax({
                type: "GET",
                url: //Set service URL,
                dataType: "json",
                headers:{Authorization: "Basic " + btoa(userName + ':' + password)},
                success: function (data) {
                    var trHTML = '';
                    $.each(data, function (i, item) {

                        trHTML += '
'
+ data[i].ProcessId + '

'
+ data[i].FileName + ''
+ data[i].StageSource + ''
+ data[i].EndTime + ''
+ data[i].Status + ''
+ data[i].EmailTo + '';
                    });

                    $('#tblProcess').append(trHTML);
                },
                error: function (result) {
                    alert(result.statusText);
                }
            });

         });

No comments: