Is there anyway to submit a form but have it remain on the page?
Right now I'm displaying a table of objects, but each row has an editable value with each row in its own Ajax form but when I click the update button it goes to the method alright but the whole page changes.
Is there anyway to submit a form but have it remain on the page?
Of course, you could use AJAX:
#using (Html.BeginForm())
{
... some form input fields
<input type="submit" value="Go" />
}
and then unobtrusively AJAXify this form in a separate file:
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
// TODO: handle the results of the AJAX call
}
});
return false;
});
});
and to avoid writing all this javascript code you may take a look at the excellent jquery.form plugin:
$(function() {
$('form').ajaxForm(function(result) {
// TODO: handle the results of the AJAX call
});
});
Another alternative is to use the ASP.NET MVC 3 Ajax.BeginForm helper:
#using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "success" }))
{
... some form input fields
<input type="submit" value="Go" />
}
and then have a success handler in javascript:
function success(result) {
// TODO: handle the results of the AJAX call
}
you will also need to include the jquery.unobtrusive-ajax.js script in addition to jquery to your page if you want to use the Ajax.* helpers.
Related
I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.
I have an application that uses the jQuery Datatable and I want to click on a row, pick up the id, and then bring up a view that allows for editing of that view and updating the underlying database.
Ajax gets me to the controller-action that for the edit view but I can't get the view itself to display. Instead, the controller action just returns to ajax. I've tried numerous tactics with no joy. Here is a simple example based upon a standard CORE template:
#section scripts{
<script>
$(document).on('click', 'button.number', function () {
alert($(this).val());
$.ajax({
method: 'GET',
url: '#Url.Action("About", "Home")'
});
});
</script>
}
<h3>Home Page</h3>
<div>
<button href="#" type="button" class="number" id="one" value="1">1</button>
<button href="#" type="button" class="number" id="two" value="2">2</button>
</div>
Running the debugger shows that About action is called OK but the view isn't rendered - it just returns to ajax. I've tried all sorts of redirection but any "return" just goes back to ajax.
Is there away around this or perhaps a better way to get from the JS to the controller-action? Thanks
EDIT:
Batuhan gets the credit for his solution but I'm re-posting it to clean up a little syntax and add the parameter passing that was my initial goal.
$(document).on('click', 'button.number', function () {
var id = $(this).val();
alert(id);
$.ajax
({
method: 'GET',
url: '#Url.Action("About", "Home")',
}).success(function (result) {
window.location.href = '/home/about/' + id;
});
});
And here is Home Controller for the About Action:
public IActionResult About(int id)
{
string parm2 = id.ToString();
ViewBag.msg = parm2;
return View();
}
And the About page:
#{
ViewData["Title"] = "About";
}
<p>
<h1> #ViewBag.msg </h1>
</p>
All works as initially hoped for!
$(document).on('click', 'button.number', function () {
alert($(this).val());
$.ajax({
method: 'GET',
url: '#Url.Action("About", "Home")'
}).success: function(result){
///this line
window.href='redirect url';
}});;
});
this is a solution cause you cant redirect from ajax call. it returns The view in html form So if you want to postback you needto use window.href="url";
I am using MVC3, Razor, C#, JQuery and AJAX.
I am using an Ajax call to postback a form to the server. I get all the form element values being passed back to the controller in:
[HttpPost]
public ActionResult Edit(Product myProduct, string actionType)
if (actionType == "Save")
save....
And in the View I have:
#using (Html.BeginForm("Edit", "RA", FormMethod.Post, new { #class = "editForm", #id = "frmEdit" }))
Form Elements:
<td>
#Html.HiddenFor(p=>p.Id)
<button type="submit" name="actionType" value="Save" >Save</button>
</td>
<td>#Html.EditFor(p=>p.Name)</td>
Some Ajax:
$('.editForm').on('submit', function () {
$.ajax({
url: this.action,
type: this.method,
data: $('#frmEdit').serialize(),
context: $('button', this).closest('tr'),
success: function (result) {
$(this).html(result);
}
});
return false;
});
Now I think the problem line is since I have seen quite a few posts about problem with JQuery and submitting button values:
data: $('#frmEdit').serialize(),
But I cannot get the button to submit an actionType of "Save". I just get null.
Thoughts greatly appreciated.
Thanks.
UPDATE:
My code seems to interfere with my JQuery listener ?? My code is:
<input type="submit" id="btn" name="btn" value="Save" onclick="document.getElementById('actionType').value = 'Save';"/>
From the documentation:
No submit button value is serialized since the form was not submitted using a button.
However you can add it by hand:
data: $('#frmEdit').serialize() + '&actionType=Save',
or
data: $('#frmEdit').serialize()
+ '&'
+ encodeURIComponent(button.name)
+ '='
+ encodeURIComponent(button.value),
where button is the <button> DOM element.
I am rendering a form in Asp.net MVC with a submit button. The page redirects after successful record addition into the database. Following is the code :-
[HttpPost]
public ActionResult Create(BrandPicView brandPic)
{
if (ModelState.IsValid)
{
if (!String.IsNullOrEmpty(brandPic.Picture.PictureUrl))
{
Picture picture = new Picture();
picture.PictureUrl = brandPic.Picture.PictureUrl;
db.Pictures.Add(picture);
brandPic.Brand.PictureId = picture.Id;
}
db.Brands.Add(brandPic.Brand);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
But, while testing, I saw that if the form is clicked again and again, the multiple entries are submitted and saved into the database.
How can i make sure that if the form has been submitted once to the server, then no duplicates are submitted.
I don't think this is quite a duplicate of the answer referenced in the comment, since the link is for spring MVC, and this question is for .NET MVC.
I actually spent a few hours on this a while back, and came up with the following. This javascript hooks nicely with the unobtrusive jquery validation, and you can apply it to any form that has <input type="submit". Note that it uses jquery 1.7's on function:
$(document).on('invalid-form.validate', 'form', function () {
var button = $(this).find(':submit');
setTimeout(function () {
button.removeAttr('disabled');
}, 1);
});
$(document).on('submit', 'form', function () {
var button = $(this).find(':submit');
setTimeout(function () {
button.attr('disabled', 'disabled');
}, 0);
});
The setTimeouts are needed. Otherwise, you could end up with a button that is disabled after clicked even when client-side validation fails. We have this in a global javascript file so that it is automatically applied to all of our forms.
Update 16 Nov 2020 by #seagull :
Replaced selector input[type="submit"] with :submit so it will work with <button type="submit" /> as well
The solution for mvc applications with mvc client side validation should be:
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});
Disable the button on Submit clicked. This can be done using JQuery/Java Script.
Look at this example on how to do this.
You can use this one. It includes unobtrusive jQuery validation.
$(document).on('submit', 'form', function () {
var buttons = $(this).find('[type="submit"]');
if ($(this).valid()) {
buttons.each(function (btn) {
$(buttons[btn]).prop('disabled', true);
});
} else {
buttons.each(function (btn) {
$(buttons[btn]).prop('disabled', false);
});
} });
For jQuery validation please incllude
~/Scripts/jquery.validate.min.js
~/Scripts/jquery.validate.unobtrusive.min.js
You can use ajax.BeginForm insted of html.BeginForm to achieve this, if you use OnSuccess insted of OnBegin you can be sure that your method execute successful and after that your button turn to deactivate,with ajax you stay
in current view and you can update your current view instead of redirection
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dive",
OnBegin="deactive"
}))
{
//body of your form same as Html.BeginForm
<input type="submit" id="Submit" value="Submit" />
}
and use this jquery in your form:
<script type="text/javascript" language="javascript"> function deactive() { $("#Submit").attr("disabled", true); }</script>
be careful for using ajax you have to call this scrip in the end of your page
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Disabling the button is fine via JavaScript but what if the user has it disabled or they bypass it? If you use client side security then back it up with server side. I would use the PRG pattern here.
window.onload = function () {
$("#formId").submit(function() {// prevent the submit button to be pressed twice
$(this).find('#submitBtnId').attr('disabled', true);
$(this).find('#submitBtnId').text('Sending, please wait');
});
}
In ASP.Net MVC 3.0 i am using a Ajax.Beginform
and hitting a JsonResult
on success of the form i am calling a jQuery Function.
but for some reason my form is redirecting to JsonAction
my View
#using (Ajax.BeginForm("ActionName", "Controller", null, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ShowResult"
}, new { id = "myform" }))
{
// All form Fields
<input type="submit" value="Continue" class="button standard" />
}
My controller
public JsonResult ActionName(FormCollection collection)
{
return Json(new { _status },JsonRequestBehavior.AllowGet);
}
jQuery
<script type="text/javascript">
function ShowResult(data) {
// alert("I am at ShowResult");
if (data.isRedirect) {
window.location.href = json.redirectUrl;
}
}
for some reason, when i click submit.
it runs the JSonResult and redirects the page to host/controller/actionname
I have included my
<script src="#Url.Content("jquery.unobtrusive-ajax.min.js")"></script>
in my layout.cshtml
can any one tell me what could be wrong?
I found the problem. Now i have to find the solution
on submit
I am validating my form
$("#myform").validate({
submitHandler: function (form) {
// my logic goes here....
}});
If i exclude the validation Ajax form works as expected.
But if i validate my form then ajax form is not working as expected
Thanks
when this happens its almost always because your script files aren't loaded
note from:
http://completedevelopment.blogspot.com/2011/02/unobstrusive-javascript-in-mvc-3-helps.html
Set the mentioned flag in the web.config:
Include a reference to the jQuery library ~/Scripts/jquery-1.4.4.js
Include a reference to the library that hooks this magic at ~/Scripts/jquery.unobtrusive-ajax.js
So load up fiddler http://fiddler2.com and see if the scripts are being called and loaded.