I have a controller LessonController with an action save(). My route for this action is POST /save LessonController.save(name: String). The code is very simple for this action.
public static Result save(String name){
Lesson lesson = new Lesson();
lesson.setTitle(name);
lesson.save();
return ok(lesson.getLessonId().toString());
}
Here is my ajax call from the view
myJsRoutes.controllers.LessonController.save(name).ajax({
success : function(id){
alert('Success');
}
});
This code does create a lesson but it refreshes the page and does not execute the success block from ajax request. I guess it is because I am returning a Result type back. I tried changing the return type to String but it gave me a compilation error.
So the question is, How can I call an action in a controller with ajax without the page refresh behaviour?
If you get a page refresh from that then it is for some other reason. Like for example triggering the ajax call with a submit button and not consuming the button event so that it leads to a form submit POST or GET
Please check you AJAX call event, may but you are triggering the AJAX call using submit button or may be you are submitting any form in the web page with the same event.
Related
I have been trying to clear my registration form after successful registration so that it can return the same form empty without reloading the entire page. please am workiing with ajax and still new to it
jQuery:
$("#formID")[0].reset();
or in javasscript
document.getElementById("formID").reset();
you could reset the values of the form as long as you use it within success() or complete() callback function
I'm having a website http://1008designs.in/ There in the home page I have built a Enquiry Form, The form usual validation works fine, but I need Jquery & Ajax validation, the form submits to 'enquiry/add', Pls help me on how to use Jquery Ajax in cakephp 2.0, I gone through a video of Andrew Perkins, but It didn't work for me. If I submit the form, then the whole home page is displayed on that Enquiry Div. I'm trying it from a week, but not working, pls help me as soon as possible.
When you submit form with ajax to controller enquiry/add the html returend by ajax request is a view associated with this enquiry/add. If you want to customize this html you have to modify add action in controller:
At the end of the action try this:
if($this->request->is('ajax'))
{
$this->autoRender = false;
$this->render('/elements/enquiry_success');
}
And in app/view/elements/ add enquiry_success.ctp containing some html/php code which will be returned to #succces div (for example <p>Enquiry added!!!</p>).
This code detects if request is ajax and id it is it doesnt render default view for action but some element.
Although I read dozens of answers I could not find a solution.
I'm using MVC 3 with Razor. I have a simple Form with client validation via ajax. This part works fine. My problem is: In the update Action of my Controller I want to redirect to another Action. If the user disables Javacript, this works fine. But with javascript/ajax enabled, the redirectaction doesn't seem to work. Instead it looks like if some kind of partialview or something like that is executed.
My Controller/Action-code:
Function UpdateItem(Item As CItem) As ActionResult
' some validation code, save etc.
if everythingok then
Return RedirectToAction("Updatesuccess")
else
Return RedirectToAction("EditItem")
endif
End Function
My html page looks like (shortened/pseudo):
Logo image
H1
some text
<form>....</form>
When the form is submitted via ajax the new html code is added beyond "some text", so the form is replaced but everything above the replaced form stays on the page.
When ajax/javascript is disabled then after submit a whole new page is loaded. I checked the http headers and noticed, that with ajax there is no redirect (which is logical in some way because it is ajax).
What can I do? I want to redirect to a new page.
Is it possible to disable the ajax-submit and only use the "normal" form-submit?
I like the client validation via ajax while the user enters data and I want to use this, but for me it would be good enough, if the submit would be a "normal" submit.
I hope someone understands what I want and can help me.
Thanks.
I'm not a 100% sure I understand your question, but what the heck, don't downvote me :)
The problem is, redirect works via sending a HttpResponse with the redirect indicated in the headers, which the browser understands. If you submit via AJAX, it's not the browser that handles the request, it's your OWN JS code.
Here is the trick: instead of returning a redirect, return the Url (preferably as json), and then redirect manually using window.location.
I'm not fluent in VB, here is how I'd do it in C#:
var url = new UrlHelper(this.ControllerContext.RequestContext);
var link = url.Action("UpdateSuccess");
return Json(new {link});
and then in jQuery:
$.ajax({ method: 'POST',
url: 'your post url',
success: function(result) {window.location = result.link; },
// ... (passing form etc)
});
From my view I am sending via $.ajax a JSON object to my controller to save it in the database.
If all succeeded i want to redirect to another action which will show a diferent view.
If i use this code:
return RedirectToAction("CreatePage", "Survey", new {id = question.PageId});
The execution goes to the Survey controller which returns a view but it is not shown.
I have read some post which said that it is not posible to redirect via ajax.
The solution I use so far is to redirect via javascript like this:
success: function (ret) {
window.location.href = "/Survey/CreatePage/" + $("#PageId").val();
}
Although this always works, sometimes i need to refresh the CreatePage view to show the last changes made.
Any idea of how to solve this problem better?
Thanks in advance
As mccow002 suggested, I wasn't really needing to make the call via AJAX for that part. After studying the solutions suggested, i realized that i could simple submit it in a form. My confusion came because I have a save and continue editing and a save. For the save and continue I use the AJAX call, but for the save option with the form being submitted is ok.
Thanks very much for your help.
Instead of redirecting to a new page, you can send a rendered html from .net code back to client and load that html in page, like this $("#main").load(renderedHtml).
But for refreshing the page you can write a simple script that run at specified intervals and refresh the page contens.
You could use [OutputCache] on the CreatePage action so that it doesn't cache the page or only caches for so long.
output caching
I'm trying to figure out how to call an action from an MVC view, not call a view URL.
I have an Action Method for signing off in the Account Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SignOff()
{
authenticationService.SignOut();
return View("SignOff");
}
And I'd like to call it from a cshtml page, like this:
<li>#Html.Action("SignOff","Account")</li>
The list is part of a drop down menu.
ActionLink doesn't work because I don't have an Account/SignOff page. The above code returns the following: "Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'." ActionLink just tells me the resource doesn't exist.
Is there anyway to do this? I just want users to be able to select a "Logout" item from a menu and then have the application call the SignOff method. Do I need to use Ajax? Javascript? I'm still experimenting. Thank yoU!
EDIT: Ok, it was the http.post that was keeping me from calling this directly. I got rid of the acceptverbs attribute and now I can call the method directly.
You can just redirect to the Login page or to any other public page (home page).
return RedirectToAction("Login");