Simple AngularJS, AJAX, and ASP.NET MVC example - ajax

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;
});
});

Related

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

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.

how to make ajax call on same page ajax request send and get in same page

here is ajax code i'm implement this code
i want to call ajax request same page where i want to get the request mean same page send request and get request
function data(status)
{ $.ajax({
type:"post",
url:"main.php",
data: "status="+ status,
success:function(data)
{
} }); });
i'm try this code but have problem in ajax call same html page show header footer also result
how to call on self page where is ajax code how it is possible?
In your success callback, do the necessary DOM update.
"data" will contain the actual response text from thte page main.php.
Your html should look like something like this:
<html>
<head>
<title></title>
<script src=[jquery JS file]"></script>
</head>
<body>
<div id="mydiv"></div>
</body>
<script>
function data(status)
{ $.ajax({
type:"post",
url:"main.php",
data: "status="+ status,
success:function(data)
{
$("#mydiv").html(data);
}
});
}
</script>
</html>
Here is the code:
$.ajax({
url:'main.php',
mtype:'post',//use mtype as 'get' for get reuest,
contentType:'application/json',
async:true, // for asynchronous calls
sucess:function(data)
{
},
error:function(error)
{
}
});

Calling server side method with 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...

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