Calling server side method with AJAX - ajax

I am trying to call a simple server-side HelloWorld method written in C# with an AJAX request.
Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type ="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
function AjaxCall() {
$.ajax(
{
type: 'post',
url: 'Default.aspx/Server_HelloWorld',
datatype: 'json',
success: function (result) { alert(result); }
})
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="Scriptmanager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
<asp:Services>
<asp:ServiceReference Path="TradeService.asmx" />
</asp:Services>
</asp:ScriptManager>
<button id="Button2" type="button" runat="server" onclick="AjaxCall()">AJAX+JQuery version</button>
</form>
</body>
</html>
Default.aspx.cs
namespace AJAXService
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public String Server_HelloWorld()
{
return "Hello, How are you?";
}
}
}
However, instead of returning the string, "Hello, How are you?", I get back the html code of the web page. Does anyone know why this happens? I am eventually trying to have a server-side method return a string that I can use to fill a GridView cell, utilizing AJAX's partial postback feature.

try this
[WebMethod]
public static String Server_HelloWorld()
{
return "Hello, How are you?";
}
So use WebMethod and static.

Yes, I think I do know why this happens! I've been having the same issue myself and have done some research.
Try using onclick="AjaxCall(); return false;". This cancels the usual ASP.NET onclick event (which in this case would do nothing but return to your page, that's why you're getting the page as response) and only execute your JavaScript method.
(Yes, I realize that I'm about 2 years too late, but I'll throw it out here for the ones facing the same issue).

Use the Following Code and Check whether you still facing the problem or not,
your Ajax Call Javascript Method....
function AjaxCall() {
$.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Server_HelloWorld',
datatype: 'json',
success: function (result) { alert(result.d); }
})
}
Add following namespaces
using System.Web.Services;
using System.Web.Script.Services;
Your aspx.cs Ajax Webmethod,
[WebMethod]
[ScriptMethod]
public String Server_HelloWorld()
{
return "Hello, How are you?";
}
Hope this helps...

Related

Spring boot ajax error with resolving template

My index.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
(js and css)
</head>
<body>
<div>
<button name="sendPaperByMessage" th:if="${paper.issend} ne 'sended'" th:paperId="${paper.paperid}">sendMessage</button>
</div>
<script th:inline="javascript">
$("button[name='sendPaperByMessage']").click(function () {
var paperId = $(this).attr("paperId");
$.ajax({
url: "/api/sendMessage",
type: "post",
data: {"paperId": paperId},
success: function (data) {
console.log("success");
}
})
});
</script>
</body>
</html>
and my controller:
#PostMapping("/api/sendMessage")
public Object sendMessage(#RequestParam("paperId") String paperId){
// paperService.sendMessage(paperId);
Map map = new HashMap();
map.put("Message", "success");
return map;
}
I omitted some code and make a demo.
the response is Error resolving template [api/sendMessage], template might not exist or might not be accessible by any of the configured Template Resolvers"
By default a Controllers returned value is resolved by spring.
In order to prevent this and return your object as json use #ResponseBody above your method or use RestController instead of Controller.
But note that in rest controllers every response is considered not to be a template and thus is not resolved.

AJAX post request error 404

I'm trying to do a AJAX post from index.html in the root to my controller. But it is returning 404 Not Found in the firefox console.
index.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax(
{
url: "api/postData",
type: "POST",
dataType: 'json',
success: function (result) {
console.debug(result);
alert(result);
},
error: function (xhr, status, p3, p4) {
console.debug(xhr);
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
alert(err);
}
});
</script>
</body>
</html>
My Controller:
namespace MyAPI.Controllers
{
[Route("api/postData")]
public class MyAPIController : ApiController
{
[HttpPost]
public bool Post()
{
return true;
}
}
}
Do I need to set something in the RouteConfig.cs?
Thanks
Update your AJAX url to include the method:
url: "api/postData/Post"
You could also try changing:
type: "POST"
to
method: "POST"
Your url is not correct. The url that you have specified leads to the controller itself. And, as you don't have a default index (GET) method you have to specify a route for the method itself:
namespace MyAPI.Controllers
{
[Route("api")]
public class MyAPIController : ApiController
{
[HttpPost]
[Route("postData")]
public bool Post()
{
return true;
}
}
}
this will make your desired url to be the one you are currently using.
Ither option is to remove both of the routes. Then your url will be myapi/post.
Check the Documentation for more information and options.

Partial View is not rendering properly, after JQuery Ajax submit

I submit a form post in Asp.Net MVC Partial View with JQuery Ajax.
The Partial View is inside one of the tabs in bootstrap tabs (there is 4 tabs and each tab has its Partial View). And there is a View, which covers all these tabs. And there is a Layout which covers all.
This is Partial view Action method call inside the cover View:
#Html.Action("AddProductPartial", "Products")
Partial View Action:
[HttpPost]
public ActionResult AddProductPartial(ProductCategoryBrand pcb)
{
if (ModelState.IsValid)
{
Product p = new Product();
p.CategoryID = Convert.ToInt32(pcb.CategoryViewModel.Kategori);
p.BrandID = Convert.ToInt32(pcb.BrandViewModel.BrandName);
p.ExchangeName = pcb.ExchangeViewModel.ExchangeName;
ProductRepository prep = new ProductRepository();
prep.AddProduct(p)
}
loadBrands();
getRates();
return View(pcb);
}
JQuery Ajax:
$('#saveProduct').click(function () {
$.ajax({
url: "/Products/AddProductPartial",
type: 'POST',
data: "{'CategoryID':" + categoryID + ", 'BrandID':" + brandID + ",'ExchangeName':" + exchangeName + "}",
async:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert(xhr.responseText)
}
});
});
These statements below populates dropdownlisfor from db. I added these methods because dropdownlistfor in the partial view was giving null exception after Ajax submit.
loadBrands();
getRates();
After adding these statements, the problem occured.
After submit, Partial view is rendering weird: Bootstrap nav-tabs are no longer visible. Because the View that covers the Partial view is not rendering at all. When I change this line:
return View(pcb);
to
return Partial View(pcb);
Then renders only the Partial view itself, independently from the all layout.
Could you please help. Thanks.
Here is the simplest example of partial view:
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult GetXlFile()
{
return PartialView("_ExcelGrid");
}
public ActionResult GetXlFile(int? id)
{
return View();
}
_ExcelGrid.cshtml in shared:
A Partial View Info
View:
<!DOCTYPE html>
#*credit to
https://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor*#
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index800</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('#pvButton').click(function (event) {
$.ajax({
url: this.action,
type: "POST",
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<div>
<input id="pvButton" type="button" value="OK" />
<div id="result"></div>
</div>
</form>
</body>
</html>

Simple AngularJS, AJAX, and ASP.NET MVC example

I would like to see an extremely minimalistic example of AngularJS making an AJAX call to an ASP.NET MVC action method. I have tried to do this myself with no success. Here is my example code...
The MVC action method...
public string Color()
{
return "red";
}
The HTML...
<!DOCTYPE html>
<html ng-app ="ColorApp">
<head>
<title>ColorApp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="/Scripts/app.js"></script>
</head>
<body>
<div ng-controller="ColorController">
{{color}}
</div>
</body>
</html>
The JavaScript...
var colorApp = angular.module('ColorApp', []);
colorApp.controller('ColorController', function ($scope) {
$http({
url: '/home/color',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.color = data;
});
});
Some things to consider:
If I replace the $http method with something like $scope.color = 'purple'; then my view renders the word "purple" as expected.
If I leave everything as is but replace the AngularJS with jQuery, everything works as expected (I get "red").
I tried changing {{color}} to {{color()}} but it made no difference.
I tried changing the action method to a JsonResult and returning Json("red", JsonRequestBehavior.AllowGet); but this made no difference either.
I appreciate your help!
add $http to your controller
colorApp.controller('ColorController', function ($scope,$http) {
$http({
url: '/home/color',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.color = data;
});
});

Is there a way to get Internet Explorer not to wait until an AJAX request completes before following a link?

I have a html page that displays some basic account information and begins a long-ish running jQuery AJAX request to retrieve more detailed data. While the Ajax request is in progress it is possible for the user to click a button that has an onclick event to navigate to a new page using location.assign.
Unfortunately if the button is clicked before the ajax request is complete nothing will happen until the ajax request completes. This is a live server issue. I want the user to be able to immediately navigate away. FF and Chrome appear to behave better but since this is a corporate intranet application they are not really an option.
The following code is similar to the page in question:
<html>
<head>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"> </script>
<script type="text/javascript">
<!--
$(function () {
jQuery.ajax({
type: 'GET',
url: '/long-running-partial-html-ajax-endpoint',
success: function (result) {
$('#detail').html(result); });
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$('#detail').html('Failed to load additional information:<br />' + textStatus + '<br />' + errorThrown);
}
});
});
//-->
</script>
</head>
<body>
<h2>Account Information</h2>
<div>Some basic details here</div>
<div><button onclick="location.assign("/somewhere-else")" type="button">Go somewhere else now</button></div>
<div id="detail">
<img src="/ajax-loading-animation.gif" alt="Loading ..." />
Loading ...
</div>
</body>
</html>
Things I've tried in the debugger (not on live) already:
using a plain anchor rather than a scripted button
using xhr.abort() before the location.assign
put alerts around the location.assign to reassure myself that the code is executing when expected
Observation:
IE stops animating the gif as soon as the button is clicked.
FF/Chrome must automatically abort the ajax request as the jQuery ajax error event is fired
Has anyone come across this issue before? Have you a resolution that will make the navigation more responsive?
Have you tried to call the ajax method after the page is loaded
<body onload="myFunctionThatCallsAjax()">
There are some browser behavior differences when you embed Javascript in the HTML code. Using onload will ensure this is not an issue.
I ended up executing the long running task in a separate thread on the server. The ajax call then just repeatedly calls in to check if a response is ready yet. That way each ajax request is very short.
My solution is fine for a intranet application but would probably need to be made more robust for a Internet application.
So the html becomes:
<html>
<head>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"> </script>
<script type="text/javascript">
<!--
var detailRequest = null;
function StartDetailRequest() {
detailRequest = jQuery.ajax({
type: 'GET',
url: '<%= Url.Action("EnquiryDetail", "Account", new { requestGuid = ViewData["detailRequestGuid"] }) %>',
success: function (result) {
if (result.length == 0) {
setTimeout("StartDetailRequest()", 500);
}
else {
$('#detail').html(result);
$("table tbody").each(function () { $("tr:odd", this).addClass("odd"); });
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$('#detail').html('Failed to load additional information:<br />' + textStatus + '<br />' + errorThrown);
}
});
}
$(function () {
setTimeout("StartDetailRequest()", 500);
});
//-->
</script>
</head>
<body>
<h2>Account Information</h2>
<div>Some basic details here</div>
<div><button onclick="location.assign("/somewhere-else")" type="button">Go somewhere else now</button></div>
<div id="detail">
<img src="/ajax-loading-animation.gif" alt="Loading ..." />
Loading ...
</div>
</body>
</html>
On the server side I do something like (ASP.NET MVC 2 with pseudo code):
private Dictionary<Guid, DetailRequestObject> detailRequestList = new Dictionary<Guid, DetailRequestObject>();
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string id)
{
var model = GetTheBasicDetails(id);
var request = CreateDetailRequestObject(id);
CheckForTimedOutDetailRequests();
detailRequestList.Add(request.Guid, request);
ViewData["detailRequestGuid"] = request.Guid;
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult EnquiryDetail(Guid requestGuid)
{
DetailRequestObject detailRequest = detailRequestList[requestGuid];
if (detailRequest == null)
{
throw new TimeoutException("Timed out retrieving details");
}
else if (!detailRequest.IsComplete)
{
return Content("");
}
else
{
var details = detailRequest.Response();
return PartialView(details);
}
}
The DetailRequestObject class encapsulates the creation of a separate thread using the async model of your choice, sets a flag when complete and collects the response data.
I also have a method CheckForTimedOutDetailRequests that collects requests that have timed out for retrieving so that any that have been 'aborted' can be cleared up.
I think I would prefer to have the long running requests run in a separate Windows Service that would do it's own clean-up, request throttling and such but the above works so...

Resources