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.
Related
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.
I was working on PayU Payment gateway integration in Spring MVC where i was supposed to use the jars of already implemented java classes. In order to do that i created a controller class where i call the required methods of the included jars. Now when i am making the ajax request it is showing me the following error:
Failed to load
http://localhost:8081/ABHI/payupg/payReqHDFC/600/SAU/Robert/robert#gmail.com/9876543210?{}:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My Ajax request is as follows:
<html>
<head>
<script type="text/javascript" src="C:/Users/myFolder/Desktop/code_testing/jquery.js"></script>
<script type="text/javascript">
function test(){
var testData = {}
//var testData = {"userName":"robert","password":"Test#12345"}
var URL= "http://localhost:8081/ABHI/payupg/payReqHDFC/600/SAU/Robert/robert#gmail.com/9876543210";
$.ajax({
url : URL,
async :false,
type : 'GET',
dataType : 'json',
data: JSON.stringify(testData),
contentType : 'application/json',
mimeType : 'application/json',
crossDomain : true,
success : function(data) {
console.log(JSON.stringify(data,null,4));
alert(data);
},
error : function(data, status, er) {
console.log(JSON.stringify(data,null,4));
console.log("Errors : "); //+data.responseJSON.errorMessage
}
});
}
</script>
</head>
<body>
<button onClick="test()"> Click me </button>
</body>
</html>
My PayUController.java is:
#Controller
#RequestMapping(value = "/payupg")
public class PayuController {
#Autowired
HdfcController hdfcController;
#RequestMapping(value = { "/payReqHDFC/{amount}/{productInfo}/{firstname}/{email}/{phone}" },
method = {org.springframework.web.bind.annotation.RequestMethod.GET })
public String paymentGateway(Model model, #PathVariable String amount, #PathVariable String productinfo,
#PathVariable String firstname, #PathVariable String email, #PathVariable String phone) throws Exception {
System.out.println("inside controller");
String str=hdfcController.payReqHDFCGateway(model,null,amount,productinfo,firstname,email,phone,null,null,null,null,null,null,null,null,null);
System.out.println("End of inside controller");
// return "hdfcPayReq";
// return PGConstants.HDFC_PAY_REQ_PAGE;
return str;
}
}
For more clarification i would like to say you can avoid the CROS-Origin issue.
In this Payment gateway almost 15 parameters are the there to be sent out of which 5-6 are mandatory. I am sending those only and rest i am setting null.
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>
I'm trying to use the Yammer API to create a post on Yammer,
I have the following code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/TR/html5/">
<head>
<meta charset="utf-8" />
<title>YammerNotification - Version 1</title>
<script src="https://assets.yammer.com/platform/yam.js"></script>
<script>
yam.config({ appId: "APP-ID" });
</script>
</head>
<body>
<button onclick='post()'>Post on Yammer!</button>
<script>
function post() {
yam.getLoginStatus(function (response) {
if (response.authResponse) {
yam.request(
{
url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body": "This Post was Made Using the Yammer API. Welcome to the Yammer API World." }
, success: function (msg) { alert("{Post was Successful!}: " + msg); }
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
)
} else {
yam.login(function (response) {
if (!response.authResponse) {
yam.request(
{
url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body": "This Post was Made Using the Yammer API. Welcome to the Yammer API World." }
, success: function (msg) { alert("{Post was Successful!}: " + msg); }
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
}
});
}
});
}
</script>
</body>
</html>
Although what would my APP ID be? And how do I tell it what group I want to put a post to?
Any suggestions are greatly appreciated
yammer
...what would my APP ID be?
You'd need to register an app as documented here - https://developer.yammer.com/introduction/#gs-registerapp and your APP ID is the client ID's value
And how do I tell it what group I want to put a post to?
Specify the groupID in your json data input:
data: {
"body": "This Post was Made Using the Yammer API. Welcome to the Yammer API World."
,"group_id" : groupID
}
See full sample code here - http://blogs.technet.com/b/israelo/archive/2014/10/21/yammer-js-sdk-for-dummies.aspx
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...