Reputation: 11
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"
Upvotes: 1
Views: 2821
Reputation: 218942
This option in your $.ajax
call.
dataType: "jsonp"
This tells that the response of this ajax call is coming from a cross domain jsonp call. jsonp is usually used for making cross domain ajax request. In the case of $.ajax
method, it will send a query string for the callback method to the server and the server is expected to wrap the result in that string (like a method call). With $.ajax, you can provide your custom local js method as the callback in the jsonp
option parameter.
When the result comes back for the $.ajax
jsonp call, jQuery will try to parse it with the expectation that the result is a string where the result is wrapped inside the callback method name. But since your server is returning raw json (without any callback prepending), the code is failing.
Ideally if you are making the call to the web api endpoint of same app, you do not need the jsonp type. Also since you are not sending any data in the request body, no need to specify the content type.
$(document).ready(function() {
var url="http://localhost:802/api/Employee/GetEmployee?Id=101";
$.ajax({
type: 'GET',
url: url,
success: function(data) {
console.log(data);
},
failure: function(data) {
alert("Failure: " + data);
},
error: function(data) {
alert("Error: " + data);
}
});
});
You might also consider using Url.RouteUrl
helper method to generate the route url to your endpoint (the method works in razor files)
var employeeUrl = "@Url.RouteUrl("DefaultApi",
new { httproute = "", controller = "Employee"})";
var url = employeeUrl + "/101";
//use url for your call
Upvotes: 1