In the previous post Part 8, we show that how to test the basic authentication web api using postman.
But if we have to consume the basic authentication web api method in Jquery, then we have to add headers attribute in ajax call.
Complete sample code as given below.
@{ ViewBag.Title = "Index"; } <script src="~/Scripts/jquery-1.10.2.js"></script> <script type="text/javascript"> function drawTable(data) { for (var i = 0; i < data.length; i++) { drawRow(data[i]); } } function drawRow(rowData) { var row = $("<tr />") $("#EmpDataTable").append(row); row.append($("<td>" + rowData.Id + "</td>")); row.append($("<td>" + rowData.EmpName + "</td>")); row.append($("<td>" + rowData.EmpAddress + "</td>")); } $(document).ready(function () { $("#btnget").on('click', function (e) { var username = "Admin"; var password = "Admin"; e.preventDefault(); $.ajax({ url: "http://localhost:64410/api/Emps_API_/2", type: "GET", cache: false, contentType: "application/json", dataType: "json", headers: { 'Authorization': 'Basic ' + btoa(username + ':' + password) } }).done(function (data) { $('#tbdata tbody').empty(); if (!jQuery.isArray(data)) data = [data]; drawTable(data); $('#btnget').prop('disabled', true); }).error(function (xhr, textStatus, errorThrown) { alert("Err " + textStatus + " " + errorThrown); }); }); }); </script> <h2>Index</h2> <table class="table table-bordered table-striped"> <tr> <td>Click Here to Received the Employee</td> <td> <input type="button" id="btnget" value="Get" /> </td> </tr> </table> <table class="table-bordered table-striped table table-hover" id="EmpDataTable"> <tr> <th>Id</th> <th>Emp Name</th> <th>EmpAddress</th> </tr> </table>
Note : in the above code headers attributes of Jquery to pass the ‘Authorization’: ‘Basic ‘ + btoa(username + ‘:’ + password), which is required to do the basic authentication process.
Here btoa is JavaScript method to convert the string to base-64 code.
Good work
Fantastic blog! Do you have any recommendations for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally overwhelmed .. Any suggestions? Appreciate it!
Yes, you can start on wordpress