Web API Using JQuery AJAX In ASP.NET MVC 5 getting error "Invalid or unexpected token"
I have created a Web API project with MVC. Which contains HomeController having Action method index
public ActionResult Index()
{
return View();
}
For above action method I would like to show employee details from ajax call in javascript alert message as
@{
Layout = null;
}
<script src="~/Script/jquery-1.10.2.min.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index<title>
<head>
<body>
<div><h2>You Are On View</h2><div>
</body>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:802/api/Employee/GetEmployee?Id=101",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: "+ data);
},
error: function (data) {
alert("Error: "+ data);
}
});
});
</script>
</html>
Also I have created one api controller as follows, which will return employee details
public class EmployeeController : ApiController
{
public Employee GetEmployee(int Id)
{
Employee objEmp = new Employee();
objEmp = ; // get data from service
return objEmp;
}
}
I am getting error like "Uncaught SyntaxError: Invalid or unexpected token" in console.
If I click on the error in console then I am getting my result as
{ "EmpId": "101","Name": "Rupesh" }
What I have tried:
I tried below solutions 1) http://www.c-sharpcorner.com/article/call-web-api-using-jquery-ajax-in-asp-net-core/
2) added headers as well & made changes in dataType from json to jsonp
dataType: "jsonp",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
3) Also I tried
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:802/api/Employee/GetEmployee?Id=101", true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
alert(xhr);
}
}
xhr.send();
4) Also added headers as
"Access-Control-Allow-Headers":"Content-Type",
"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Origin": "*",
"cache-control":"no-cache"
dataTypeproperty in your$.ajaxcall. You also don't need CORS if you're making a local request. I'd suggest using a relative path for your AJAX request too