Reputation: 17
I have written simple webapi method. I am trying to access that method in mvc using ajax call. I am getting output in browser and fiddler . But Its not working in cshtml page.Please let me know , If I have to add something. Please look into this..
function validate() {
alert("came");
$.ajax({
url: 'http://localhost:54544/api/home/getname/',
method: 'GET',
contentType: 'application/form-url-encoded',
success: function ()
{
alert("success");
},
error: function (ex) {
alert(ex.responseText);
}
});
}
check the html code here
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
// beforeSend: function(xhr, settings) { xhr.setRequestBody('Authorization','Bearer ' + token); } ,
$(document).ready(function () {
alert("came");
$.ajax({
url: "http://localhost:54544/api/home/getname/",
type: "Get",
success: function (data) {
alert("test came");
},
error: function (msg) { alert("error"); alert(msg); }
});
});
</script>
</head>
<body>
<div>
<table>
<tbody>
<tr>
<td><input type="button" value="Submit" onclick="validate()" name="Submit" /> </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
how to add request body parameters in ajax request
Upvotes: 1
Views: 1505
Reputation: 1038720
It looks like you are violating the same origin policy restriction by trying to make an AJAX call to another domain. For this to work you might need to enable CORS
in your Web API. If you are using ASP.NET Web API you may checkout the following tutorial
which illustrates how this can be done.
Basically you can install the Microsoft.AspNet.WebApi.Cors
NuGet:
Install-Package Microsoft.AspNet.WebApi.Cors
and enable CORS in your bootstrapper:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
...
}
}
Finally decorate your API controller with the [EnableCors]
attribute:
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public class ItemsController : ApiController
{
public HttpResponseMessage Get() { ... }
}
Upvotes: 1