form submission using ajax-jquery and stopping the normal html submission - ajax

i am working on a html form where i am using a jquery ajax function that is called in the tag with onSubmit but the problem is that when user presses submit button or enter, the form gets submitted and page gets refreshed and the ajax function is not executed resulting in an output that is undesired.
How can i stop the normal submission and make the form submission only using ajax function and why the ajax function is not getting executed..i even tried .submit attribute of jquery but nithing happened.
please suggest some hacks/methods to deal with it. thanks

You can prevent the default behaviour of the submit event by using
$( "#target" ).submit(function( event ) {
event.preventDefault();
});
This could be find in the JQuery documentation https://api.jquery.com/submit/

To disable form submission change your code to following:
<form action="/" method="POST" onSubmit="return comment();">
...
</form>
function comment() {
...
return false;
}
Working sample is here https://jsfiddle.net/gevorgha/5dyc2ye9/ , try changing return false; to return true; and you will see submission.

Related

Web2py: how to cancel a form submission within a LOADed component

If I have a web2py view (say tmp.load), I can force the form not to submit by returning false from the on submit handler.
<form onsubmit="return false;"><input type="text"><input type="submit" /></form>
That works when I view it directly: this form never submits. But if I load this view using
{{=LOAD('tmp.load', ajax=True)}}
Then the form submits, even though I was expecting it not to. So how do I write a LOAD component that contains a form which can be programmed not to submit if certain js conditions are met?
web2py.js automatically sets up event handlers for forms in components in order to submit them via Ajax. One possible approach is to intercept web2py's Ajax submission by setting up an ajax:beforeSend event handler. For example, in the view of the component (i.e., tmp.load), something like:
<script>
$(document).on('ajax:beforeSend', function(e, xhr, settings) {
if (settings.type === 'POST') {
if(abortAjaxSubmission) {
xhr.abort();
$.web2py.enableFormElements($('form#myform'));
}
}
});
</script>
In the above, abortAjaxSubmission represents the condition where you want to stop the submission. The selector form#myform represents the form in the component (you need to re-enable the form elements because web2py disables them upon submission but only re-enables them upon completion of the Ajax request, which won't happen if you abort).

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

jQuery.validate stops my form from being submitted

jQuery.validate stops my form from being submitted. I would like it to just show the user what is wrong but allow them to submit anyway.
I am using the jquery.validate.unobtrusive library that comes with ASP MVC.
I use jquery.tmpl to dynamically create the form and then I use jquery.datalink to link the input fields to a json object on the page. So my document ready call looks something like this.
jQuery(function ($) {
// this allows be to rebind validation after the dynamic form has been created
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($("form"));
// submit the answers
$("form").submit(function(e) {
$("input[name=jsonResponse]").val(JSON.stringify(answerArray));
return true;
});
}
I note that there is an option
$("form").validate({ onsubmit: false });
but that seems to kill all validation.
So just to recap when my form is rendered I want to show all errors immediately but I don't want to prevent the submit from working.
So after some research (reading the source code) I found I needed to do 2 things
add the class cancel to my submit button
<input id="submitButton" type="submit" class="cancel" value="OK" />
This stops the validation running on submit.
To validate the form on load I just had to add this to my document ready function
$("form").valid();
Hope this helps someone else

jquery with boxy plugin - load and submit a form via ajax

I am using JQuery with Boxy plugin.
When a user clicks on a link on one page, I call Boxy.load to load a form onto the pop-up. The form loads and is displayed inside the pop-up without problems.
However, I can't bind the form to a submit event, since I can't select the form element.
This is the event handler:
$('#flag-link a.unflagged').click (function(e) {
url = $(e.target).attr('href');
Boxy.load(url, {behaviours: function(r) {
alert ($("#flag-form").attr('id'));
}
});
});
The alert reads "undefined" when it is displayed.
And this is the form:
<form id="flag-form" method="POST" action="somepage">
<table>
<tr><td><input type="text" name = "name"></td></tr>
<tr><td><input type="submit" value="OK"></td></tr>
</table>
</form>
What am I doing wrong?
First (a minor point, but a potential source of trouble), it should be id="flag-form" not id = "flag-form" (no spaces).
Second, you shouldn't need r.find(). Just do $("#flag-form").attr("id")
As far as I understand, live() method must be used to bind an element to an event in this case:
$("#flag-form").live("submit", function(){ ... }
Presently, live method is documented to be not supporting the submit event. However, I could work it out with Chrome and FF. On the other hand, I couldn't get it working in IE. A better way for cross-browser compatibility seems to be binding the submit button of the form to the click event.
$("#flag-form-submit").live("click", function(){
I learnt that declaring methods in behaviours: function (e) {} works, in addition to using live() methods.
E.g.:
$('#flag-link a.unflagged').click (function() {
Boxy.load(this.href, {
behaviours: function(r) {
r.find('#flag-form').bind('submit', function() {
// do on submit e.g. ajax calls etc.
});
}
});
return false;
});
Boxy opens the URL (url = $(e.target).attr('href');) in an iframe. So you cannot find the form from the opening page(parent page). Your code to bind the form should be in the child page (ie, the Boxy iframe). You can check the iframe URL using your code, url = $(e.target).attr('href');

Jquery Validation Plugin, dynamic form validation

I'm using the Jquery Validation Plugin to forms loaded via Ajax (dynamic forms). I know that as of Jquery 1.4, live events on submit is now possible. Now the problem is I want to show a confirm message after the dynamic form has been validated. My code looks like this:
$('.dynamicForm').live('submit',function(){
$(this).validate();
if($(this).valid()){
if(!confirm('Are you sure?'))
e.preventDefault();
}
});
It's not working as expected. Somehow confirmation shows first, then at the second time I submit the form, that's the time the validation happens. Any ideas?
Somehow this seems to work:
$('.dynamicForm').live('mouseover',function(){
$(this).validate({
submitHandler:function(form){
if(confirm("Are you sure?")){
form.submit();
}
}
});
});
Use the submitHandler function available in the validate options:
$(".dynamicForm").validate({
submitHandler: function(form) { //Only runs when valid
if(confirm('Are you sure?'))
form.submit();
}
})
From the docs - submitHandler:
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.

Resources