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.
Related
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var data = encodeURI("<script>alert('123');</script>");
alert(data);
// Unable to get the alert('123'); in alert due to > symbol
// button click even helps in posting data on backend
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: data ,
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
The problem is that your sequence is not correctly escaped.
try
var data = encodeURI("<script>alert('123');<\/script>");
instead of
var data = encodeURI("<script>alert('123');</script>");
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;
});
});
I am trying to use ng-grid using the following tutorial.
http://angular-ui.github.io/ng-grid/
Here is my View
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.2.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/angular.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/angular-resource.js")"></script>
#*<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>*#
<script type="text/javascript" src="#Url.Content("~/Scripts/ng-grid-2.0.7.min.js")"></script>
<script src="~/Scripts/PostsController.js"></script>
<script src="~/Scripts/postreq.js"></script>
<link rel="stylesheet" type="text/css" href="~/Content/ng-grid.min.css" />
<div data-ng-controller="PostsController">
<div class="gridStyle" data-ng-grid="gridOptions"></div>
</div>
Here is my Angular code
function PostsController($scope, $http) {
$http({ method: 'GET', url: '/api/request' }).
success(function (data, status, headers, config) {
$scope.posts = data;
}).
error(function (data, status, headers, config) {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.gridOptions = { data: 'posts' };
}
However, when i run the application i see blank square in browser and there is no error showing in the console.
Please help me to fix this issue.
FYI: I checked API response directly in browser and it shows with data.
It seems to me that you are missing some steps of the tutorial you are following :
Where you declare your app module, add ngGrid:
angular.module('myApp',['ngGrid']);
I do not see your module declaration anywhere.
Do you have ng-app="myApp" defined at the top of your page?
I also noticed that you do not have a css class defined for "gridStyle". "gridStyle" is not part of the ng-grid css.
Sounds odd, but this worked for me by using a timeout. Try it like this:
setTimeout(function () {
$http.get('/api/request')
.success(function (data, status) {
$scope.posts = data;
})
.error(function (data, status) {
alert(status);
});
}, 100);
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...
Please could someone help me work out how to get started with JSONP?
Code:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
var photos = function (data) {
alert(data);
};
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: false,
});
});
Fiddle: http://jsfiddle.net/R7EPt/6/
Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).
thanks.
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?
Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";
You will end up with a script segment that looks like this after it loads the data:
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";
Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});
See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.
NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.
RAW JavaScript demonstration (simple Twitter feed using JSONP):
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
</body>
</html>
Basic jQuery example (simple Twitter feed using JSONP):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)
There is even easier way how to work with JSONP using jQuery
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.
For more detail refer to the jQuery.getJSON documentation.
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here