How to Consume Web API in JQUERY ajax
1) Create a HTML Page/ASPX Page etc.,
2) Add following input elements and 4 buttons for POST,DELETE,PUT,GET
3) Div Element to display all results
<b>Id:</b><input type="text" value="" id="txtId" /><br />
<b>cusomer Name:</b><input type="text" value="" id="txtName" /><br />
<b>Date Joined:</b><input type="date" value="" id="doj" /><br />
<b>EmailID:</b><input type="email" value="" id="txtEmail" /><br />
<b>Mobile:</b><input type="text" value="" id="txtMobile" /><br />
<input type="button" value="POST" onclick="javascript: CustomerWebApi('POST')" />
<input type="button" value="PUT" onclick="javascript: CustomerWebApi('PUT')" />
<input type="button" value="DELETE" onclick="javascript: CustomerWebApi('DELETE')" />
<input type="button" value="GET" onclick="javascript: CustomerWebApi('GET')" />
<br />
<div id="cusomersTbl"></div>
4) Add JQUERY Ajax function to do CRUD operations on Web API
<script type="text/javascript">
function CustomerWebApi(verb) {
var customerJson = getmyjson(verb);
alert(customerJson+getUrl(verb));
var rquest=$.ajax({
type: verb,
url: getUrl(verb),
async: true,
data: getmyjson(verb),
dataType:"json"
});
rquest.done(function(customer)
{
alert(customer);
DisplayData(customer);
});
rquest.fail(function (jqXHR, textStatus) {
alert(textStatus+jqXHR.statusCode);
});
}
function getUrl(verb) {
var URL="http://localhost:42340/api/customer";
if (verb == "DELETE" || verb == "PUT") URL = URL + "/" + document.getElementById("txtId").value;
return URL;
}
function getmyjson(verb) {
var jsonCustomer="";
if (verb == "POST" || verb == "PUT") {
var isoDate = new Date($("#doj").val()).toISOString();
var customer = {
custId: $("#txtId").val(),
Name: $("#txtName").val(),
DOJ:isoDate,
szEmailID:$("#txtEmail").val(),
Mobile:$("#txtMobile").val()
}
return customer;
}
else if (verb == "GET" || verb == "DELETE");
return jsonCustomer;
}
function DisplayData(customers) {
var divE = document.getElementById("cusomersTbl");
for (i = 0; i < customers.length; i++) {
divE.innerHTML += customers[i].custId + " " + customers[i].Name + "<br/>";
}
}
</script>
No comments:
Post a Comment