I am quite new to Spring framework and i have a problem.
I have a page A.jsp and in this page i have a link to page B.jsp
<c:url value="${pageContext.request.contextPath}" var="contextPath" />
Click here
And in controller
#RequestMapping("pageB")
public String pageBlink(SitePreference sitePreference, Device device, Model model) {
return "pageB";
}
Now on page B.jsp i want to invoke an Ajax call.
I have a link Send request
function myFunction(){
dojo.xhrGet({
// The URL of the request
url: "requestPage",
method: "POST",
handleAs: "json",
// The success callback with result from server
load: function(jsonData) {
var content = "";
dojo.forEach(jsonData.newsItems,function(locationPoint) {
// Build data from the JSON
content += "<p>" + locationPoint.name + "</p>";
content += "<p>" + locationPoint.latitude + "</p>";
content += "<p>" + locationPoint.longitude + "</p>";
content += "<p>" + locationPoint.number + "</p>";
});
},
// The error handler
error: function() {
// Do nothing -- keep old content there
},
// generate an extra GET variable to prevent browsers from caching
preventCache: true
});
}
And add into controller
#RequestMapping(value="requestPage", method = RequestMethod.GET)
public MyObj returnEVSELocations(){
logger.log(Level.INFO, "return evse locations --------------");
MyObj myObj = new MyObj();
// add some stuff into the obj
return myObj;
}
But this request a requestPage.jps ... i want just to work in my page (B.jsp).
Any help is more than welcome.
Thanks!
I found the issue.
In fact there was 2 problems
1. In Ajax call i must have
dojo.forEach(jsonData, ...) instead dojo.forEach(jsonData.newsItems, ...)
2. In the controller in on my method i must add the annotation
public #ResponseBody MyObj
I hope this help someone to front the same issue.
Related
I am new in asp.net mvc programming, please be gentle... :)
Please notice that the following views are all PARTIAL views! Methods are called through Ajax and redirect to partial views with lists, forms are posted through Ajax, etc. OK, here we go...
1st controller named AlertsController. One of the methods is ResolveAlert(Guid id) which returns RedirectToAction -> UnresolvedAlerts() which is just a list of unresolved alerts.
2nd contoller named FrontDeskController. One of the methods is CustomerDetails(Guid id) which lists the customer and alerts that he might have.
I want to be able to "Resolve an alert" (thus use the method of the 1st controller) but return to the page that I was before instead of going to the redirected page that the method returns.
I added a second parameter to the ResolveAlert() method which lists a returnUrl string. I manage to send the Url that I want it to redirect to but I get just the partial (not rendered inside the whole page as it should)...
Here's my ResolveAlert method on my AlertsController:
// Resolve Alert POST
[HttpPost]
public async Task<ActionResult> Resolve(AlertModel model, string redirectUrl)
{
await _AlertsService.ResolveAsync(model);
if (!string.IsNullOrWhiteSpace(redirectUrl))
return Redirect(redirectUrl);
return RedirectToAction("Unresolved");
}
...and here is my CustomerDetails() method on my FrontDeskController:
// Display Customer Alerts
public async Task<PartialViewResult> CustomerDetails(AttendanceModel model, Guid id)
{
var customer = await _CustomersService.ReadAsync(id);
ViewData["Customer"] = await _CustomersService.ReadCustomerExtendedAsync(id);
var alerts = await _AlertsService.ReadCustomerAlertsAsync(id);
ViewData["Alerts"] = alerts.Where(x => x.IsResolved == false).ToList();
return PartialView("_CustomerDetails", model);
}
The ResolveAlert() method of the first controller is called in two steps... 1st I call a modal from the CustomerDetails view:
function resolveAlert(alertId, customerId) {
var returnTo = '/FrontDesk/CustomerDetails/' + customerId;
$.ajax({
method: 'GET',
url: '/Alerts/Resolve/' + alertId,
data: {returnUrl : returnTo},
dataType: 'html'
}).then(function (html) {
$('#dialog-container').html(html);
showDialog();
});
}
...then on the modal I have:
#{
var data = Request.Params["returnUrl"];
}
#using (Ajax.BeginForm("Resolve", "Alerts", new { redirectUrl = data}, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "partial", OnSuccess = "hideDialog" }, new { id = "form", #class = "form-horizontal" }))
{ ..... textbox with some notes that I can post while resolving the alert ..... }
... and (finally) here is the final part at the bottom of my modal:
<script type="text/javascript">
$('#form').validate({
rules: {
AlertNotes: {
required: true
}
},
submitHandler: function (form) {
$.ajax({
url: $(form).attr("action"),
data: $(form).serialize(),
type: $(form).attr("method")
}).then(function (result) {
$("#partial").html(result);
hideDialog();
});
}
});
</script>
I think that in order for the returned partial to get rendered correctly inside its container I should be returning a RedirectToAction from the ResolveAlert() method but the problem is that it belongs on a different controller...
Is it possible to get this working somehow or should I just bite the bullet and forget about having those pages as partials, get rid of the Ajax calls and use normal Url.Action() links?
It was just a Javascript/Ajax bug in my code.... Please disregard the question...
For those wondering, I had 2 forms using the same id. JS died silently allowing the form to be posted normally and not through Ajax. It had me scratching my head for a while now. Too bad that web development tools and VS in particular can't snipe such errors and provide a meaningful hint to assist you in debugging...
I have written an Ajax POST to submit a form, but it fails to succeed.
The Ajax POST comes through to the action in the controller which in turn will return a PartialView, which is also made correctly as I can debug this.
The goal is to let the user add a new log, whatever the outcome (failed captcha, failed validation) a Partialview will be returned with the right ViewBag errors messages. Razor takes care of the rest. This way the user will not be redirected to other pages.
When the Ajax succeeds it should put the data in the right <div>. The code is a copy of a working Ajax GET only changing it into a POST and providing the formdate serialized.
tldr; Ajax POST to Action in controller works, the partialview is rendered and returned yet the Ajax failes to succeed making it unable to update the designated <div>
Ajax call:
<script>
$('#add-log').click(function (event) {
event.preventDefault();
$.ajax({
url: $('#add-log').attr('data-url'),
type: 'post',
data: $("#log-form").serialize(),
succes: function (data) {
$('#add-log').attr('data-target').html(data);
console.log("Succes");
}
});
}
</script>
Controller:
[HttpPost, ValidateInput(false)]
[Authorize(Roles = "Student")]
public ActionResult Add(object sender, Log log, string returnURL, bool SendEmail)
{
ViewBag.Vulns = TempData["Vulns"];
//region Captcha: Here we have our Captcha settings
var response = Request["g-recaptcha-response"];
//secret that was generated in key value pair
const string secret = "Just a secret for our captcha, move along";
var client = new WebClient();
var reply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));
var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);
if (ModelState.IsValid && captchaResponse.Success)
{
db.Log.Add(log);
db.SaveChanges();
if (SendEmail)
{
//Emails are sent from here on out, but that's out of the scope
}
}
else
{
if (!captchaResponse.Success)
{
ViewBag.fillcaptcha = "Please fill in the captcha";
}
else
{
ViewBag.Wrong = "Something went wrong please try again";
}
ViewBag.returnUrl = returnURL;
ViewBag.domain = log.DomainId;
return PartialView(log);
}
}
There's more code but I left that out. Most important thing in the controller is just the last IF. I test the ajax by posting an empty log with no captcha resulting in a partialview with the same log and the viewbag.captcha error. This partialview is rendered but somehow ajax doesn't succeed.
I learn ASP.NET MVC and have some issue.
I create two links by ajax helper method in view. They send mailsType argument and response json data. Here is the code of links and AjaxOptions object
<div class="list-group" style = "text-align: center; margin-top: 10px;">
#Ajax.ActionLink("Incoming", "GetMails", new { mailsType = State.Incoming }, opts,
new{#class = "list-group-item active", data_type = "Incoming"})
#Ajax.ActionLink("Outgoing", "GetMails", new {mailsType = State.Outgoing}, opts,
new { #class = "list-group-item", data_type = "Outgoing" })
</div>
Here is ajaxoption, using in ajax helpers
AjaxOptions opts = new AjaxOptions
{
OnSuccess = "viewMail",
};
I handle response by javascript function
function viewMail(data) {
var html =
'<table class="table table-hover table-striped">' +
'<thead>' +
'<tr><th>' + (data.State == 'Incoming' ? 'From' : 'To') + '</th> <th>Subject</th> <th>Date</th></tr>' +
'</thead>' +
'<tbody>';
$(data.Mails).each(function(i, el) {
html += '<tr><td>' + el.From + '</td> <td>' + el.Subject + '</td> <td>' + el.Date + '</td></tr>';
});
html += '</tbody></table>';
$('#contentDiv').html(html);
}
And here is code of action method in controller
public ActionResult GetMails(State mailsType)
{
if (Request.IsAjaxRequest())
{
return Json(new
{
State = Enum.GetName(typeof (State), mailsType),
Mails = _serviceManager.GetMessages(mailsType)
}, "application/json", JsonRequestBehavior.AllowGet);
}
else
{
ViewBag.State = Enum.GetName(typeof(State), mailsType);
return PartialView(_serviceManager.GetMessages(mailsType));
}
}
When I use second link all works good, but when I use first one, i have internal server error with code 500 and response type is text/html.
I use this links to return partialviews and they all works before.
I tried to use my own ajax request, but result was still the same. I can't understand what's wrong. I understan't that question is abstract, but may be you had same problem or know why it happens.
Edit1
When I write address from link in address bar, I have this error:
System.InvalidOperationException: Timeouts are not supported on this stream.
I tryed set big timeout in ajax request, but it didn't help. Reqest executes successfuly when I send less data in response.
I think it related with size of data sending in response. Am I wrong? What reasons of this error can be?
I will by happy all yours advice. Thanks to all!
I have already read this and this to get some help but there is something wrong in my code. Well I want to insert a form to database via Ajax and this is what i did:
The Ajax function :
<script type="text/javascript">
function doAjaxPost() {
var form = $('#ajf');
frm.submit(function () {
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/ajouter_user",
data: form.serialize(),
success: function(response){
// we have the response
$('#info').html(response);
},
error: function(e){
alert('Error: ' + e);
}
});
});
}
</script>
'#info' is the ID of the DIV where i want to show the success message returned by the controller.
this is my controller :
#RequestMapping(value="/ajouter_user",method=RequestMethod.POST)
public #ResponseBody String addUser(#ModelAttribute User us,BindingResult result,ModelMap model){
String returnText;
if(!result.hasErrors()){
model.addAttribute("us", new User());
userservice.AddUser(us);
model.addAttribute("usersystem", userservice.getAllUsers());
return returnText = "User has been added to the list." ;
}else{
return returnText = "Sorry, an error has occur. User has not been added to list.";
}
}
HTML :
<form:form id="ajf" method="POST" commandName="user">
Here are my fields ...
<input type="submit" value="Créer" onclick="doAjaxPost()"/>
</form:form>
What is wrong is : I don't get the String that the controller return , I get an alert error (object [] object ), the data is inserted to database and the page reload after submitting without giving any error
Can someone give me a toturial how to use Ajax with spring (inserting to database )
please help me
If you are using jQuery (it looks like you are), then you need to include the event in the function and do an event.preventDefault() to prevent the form from submitting. Otherwise the event will propagate up and the form will submit, and you will get the ajax post and the form post.
i have a script in my view which is:
$('.datepicker').datepicker
(
{ onSelect: function (dateText, inst) {
//pass dateText to my controller
});
</script>
my controller is like this:
public ActionResult Index()
{
string dateSelected = dateText; //read dateText here
if (DateTime.TryParse(dateSelected, out date))
{
date = Convert.ToDateTime(dateSelected);
var reservations = db.Reservations.Where(r => r.Date == date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
return View(reservations);
}
return View();
}
i want dateText to be passed to the controller without the current page being refreshed or reloaded. how to do that?
i tried forms earlier and on the onselect event of the datepicker, i automatically submit the form so the controller can accept it. but i do not want the current page to be refreshed or reloaded.
i just want to pass dateText to the controller without the user noticing the passing.. some sort of $.post i guess but i dont know how to implement it..
UPDATE: here is my try, what is wrong:
ok here is my script:
JSONstring = JSON.stringify(dateText);
$.post("/Home/Index", { jsonData: JSONstring });
here is my controller:
public ActionResult Index(string jsonData)
{
CacheClear();
string dateSelected = jsonData;
.....
//i tried to debug it, but no value of jsonData
}
i want dateText to be passed to the controller without the current
page being refreshed or reloaded. how to do that?
You could use AJAX.
use ajax and send all the variables or data in the ajax data string and provide the url of your controller for example
function add_to_cart(id , title, price,qty){
$.ajax({
type: "POST",
url: "your controller" + id ,
data: "&title=" + title + "&price=" + price +"&quantity=" + qty ,
complete: function(data) {
//alert("Item added to cart");
}
});
}