Disable action in form when using AJAX commands? - javascript

When one uses AJAX commands with Jquery, is it necessary to disable form action parameter in the HTML? The load URL and the action point to the same place, so is it necessary to have the action parameter?

You should use the event object's preventDefault() method, which will disable any default behavior associated with the element type. This is very important for links and form submit buttons.
For example:
<!-- you have this link -->
<a id="clickme" href="test.html">Click me</a>
You can disable the loading of test.html by using preventDefault()
$('#clickme').click(function(event) {
event.preventDefault();
// ...
});
You can also return false in your click function for the same effect.

In this case I think is useful only for clarity of code. When you put your code to make the AJAX call you can get the url from the form's action but that depends on you.
Try to be clear and consistent it's my advice.

If you are submitting the form via Ajax, then you just need to make sure there is not a way for the form to be submitted traditionally. You can either remove the form tags themselves, remove the actions, or remove any submit buttons. You can also capture the submit event of the form and just return false to prevent the form from doing a postback submit.

Related

Why does adding "return false;" to a submit event prevent the page from refreshing?

I'm doing a tutorial on making a chat server with Node.js and socket.io. Here's what I had in the html:
<form id='chat_form'>
<input id='chat_input' />
<button>Send</button>
</form>
<script type='text/javascript'>
var socket = io();
$('#chat_form').submit(function(){
var message = $('#chat_input').val();
socket.emit('messages', message);
$('#chat_input').val('');
});
</script>
I won't bother putting what I had on the back-end, because that part all worked fine. But in the browser, every time I submitted, the page refreshed, and a /? was added to the end of the URL bar.
Looked around for a bit, and found another tutorial (the one on the socket.io website), that had basically the same code, but they had added return false; to the end of their submit event. Tried that out and it worked fine. I'd like to understand why that worked though. Can anyone explain? Also, can you explain why the /? was added to the URL?
first about /?:
default method of form submit is GET, but you can change it with <form method="POST"> (while default is <form method="GET"> if method is not provided).
With POST form data is passed in request body, with GET - in request url params.
If you have
<form action="/submit.php" method="GET">
<input name="foo" value="1" />
<input name="bar" value="2" />
</form>
And you submit that form, you'll get URL something like /submit.php?foo=1&bar=2.
In your case you have no inputs with name attribute, so your GET params are "empty" (/?<params should go there>).
You can read more in:
http://www.w3schools.com/tags/att_form_method.asp
About return false;
Submitting form forces page reload (with either POST or GET request). If you submit form with javascript you need to prevent this default action. You can do this by
$('#chat_form').submit(function(event){
//....
event.preventDefault();
});
Or with return false;.
A simple and easy answer to this is
"Return false prevents navigation"
Return false is always used in those case where user or browser action needs to be stooped.
In every programming language, the code after return is not executed, which means further action wont take place, which can be
stopping form submit
stopping navigation and hyperlink jumps
other than return false you can also use
event.preventDefault();
event.stopPropagation();
Now about form submit
A form is submitted using GET and POST which can be decided by the author using method="POST" attribute in form tag,
when nothing given by default form submits using GET
which passes values in url - ex - something.html?para1=value1&para2=value2
which is fast and less secure, every time you submit a form with get all the form elements will be passed in the url
From the jQuery submit() docs:
Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
So what's happening is, the default event behavior triggered when the submit event occurs is being prevented.
The default method of submission for the jQuery submit function is an HTML GET, which supplies the form paramaters as a URL query, in the form of /?queryParam=value. Hence, the /? appears in the URL, with no query parameters after the /? (as none are being supplied in the form).
Hope this helps!
Return false prevents all of the default functions of html element events from firing.
An example is an html form, once you hit the submit button it's default is to navigate to another page. You don't want that to happen if you are using Ajax functions to send data to a server without leaving the page.
Another way to do it is pass an event object parameter to the event function.
Then at the beginning of the function type event.preventDefault ();.
The following link offers a good explanation of why the trailing slash is present. https://webmasters.stackexchange.com/questions/35643/is-trailing-slash-automagically-added-on-click-of-home-page-url-in-browser
your form element has no method, so default method get is set. If you click send all the input elements are added after current page+?
return false prevents the submit action to perform.

form submit not working correct with jquery

i have ajax validation function and when ajax validation is true then i use:
$("#test_form").submit();
it is work fine but any time i can click Enter and submit a form when form is not validated (skip validation process and pass wrong data).
i try put
$("#test_form").submit(function(){event.preventDefault();});
then still can submit with enter when data is wrong
or
$("#sample_form").submit(function(){false});
then i cant submit any time.
How to submit only when ajax is true?
The first part of your answer is said in the comment section :
Use $("#test_form").submit(function(event){event.preventDefault();}); notice function(event)
– Satpal
Then you'll notice an other problem, your form will never submit after the AJAX call. That is because you use $("#test_form").submit(); to submit, which is the jQuery triggering the event. When jQuery trigger the event, it will always be prevented by the preventDefault.
What you need to do is to use the native JavaScript event :
$("#test_form")[0].submit();
When you are using the native handler, the event you have been added with jQuery will not trigger. It will instead directly send the form.
In Submit button, Use onclick with return then On press enter it will check first javascript validation.

Yii and Javascript form submission

I'm using Yii as a PHP framework for my site. Additionally, my site uses some js/jquery like, say, a jQuery UI Dialog widget (except for those dialogs, the rest of the code is pure normal html form components and jQuery code for the event handlers).
In the Yii side, I use CForms to build my forms from specifications file.
When I test if the form was submitted, I must do it for a certain button. This is not only forced, but I also take advantage of it.
if ($myCFormInstance->submitted('approve')) {
//process approval code
} else if ($myCFormInstance->submitted('reject')) {
//process rejection code
}
The actual problem I have is a bit conceptual one, since -fortunately- I know what's going on with my code and -again, fortunately- know the problem root:
Somewhere in My code I intercept the submit button's click event:
$(function(){
$(".critical-action").click(function(e){
var form = $(this).closest("form");
e.preventDefault();
e.stopImmediatePropagation();
confirmDialog("¿Continuar?", "#critical-action-dialog", function(){
form.submit();
});
});
});
Say the .critical-action classed elements are always a submit button in a form.
The intention of the code: cancel the form submission, and perform it only if the user -in the dialog- clicks the "Yes, Continue" (i.e. confirming the action) button.
This code works as expected, and have no problems at a javascript level BUT -and here goes my issue- when doing form.submit(), the button is not sent as part of the form. This is obvious: I'm sending the form without specifying any button. In the case of Approve and Reject, which have two buttons, the example explains itself: if the form.submit() call could send their buttons ¿which of them should send?.
Question: So, since form.submit() doesn't send any button, but I actually need buttons ¿how can I send the form "with the corresponding button" -i.e. a button I choose to specify, which should correspond to this in the click handler function context- automatically via javascript? The button NEEDS to be identified by Yii in order to process the form (specially with the Approve and Reject case).
If you added a hidden input to the form, you can modify the input value with jQuery before you submit the form, like this:
$("#inputID").val('approve');
If you want to set the value to the value of the clicked button via $(this).val(), be aware of the issue that could result in an IE browser, explain here. The second answer (by postpostmodern) has a solution to this issue.

Intercept form onSubmit

Is there any way we can intercept the html form's onsubmit event?
In my web application, there are several screens containing forms etc. The issue we are facing is when the user presses any button multiple times, the server gets overloaded with same requests.
Some of the forms have event handlers already attached to them(like onSubmit, button.onClick etc).
One way can be to "inject" my button disable code by going through all the screens.
But what I am looking for is a generic solution which can be applied to all the screens by just including the script where the function is written.
I know I can setup callback using jQuery (capturing onSubmit for form), but in the issue in this case is if any screen has a onSubmit registered already, it may not get called.
Any help in this regard appreciated!
I think this piece of code is a good place to start. It should be placed in separate file and included where you want to use it (if you appear to have global list of scripts - its a good place for it)
var suppressed_items = [];
function allowOnlyOne(item,e){
if (jQuery.inArray(item, suppressed_items)==-1){
//hi little item, I haven't saw you before, please go on... but I remember you
suppressed_items.push(item);
return true;
}
else{
//Hey, you have been submitted already, stay where you are!
return false; //or e.preventDefault(), it's a matter of faith :)
}
}
jQuery(document).ready(function(){
//don't worry, it won't replace your `ready` handlers, but just append new handler
jQuery("from").submit(function(e){
return allowOnlyOne(jQuery(this),e);
});
});
You can use the allowOnlyOne function with any item you wish. So, for example to allow single click on all hyperlinks, inside that ready handler add:
jQuery("a").click(e){
return allowOnlyOne(jQuery(this),e);
}
I hope you get the basic idea: catch the event, get the ID of the element that trigger it, fed it to AllowOnlyOne along with event.
Of course you can wrap it all around into self-executing closure to achieve incapsulation and so on...
If you already have jQuery I suggest you use it... All you need to do is make sure is that your form's onsubmit do not have a "return false" or else it can block jQuery's on submit.
Here's what you need to do:
Remove any return false from your form's onsubmit (if any). Don't worry we'll take care of this later in jQuery.
Add a class to your forms... something like "disableOnSubmit". Example:
<form action="something" onsubmit="yourExistingCode" class="disableOnClick">
</form>
OR
<form action="something" onsubmit="yourExistingCode" class="someOtherClass disableOnClick">
</form>
Implement a code similar to:
<script type="text/javascript">
$(document).ready(function(){
$('form.disableOnClick').submit(function(e){
// preventDefault() does the same as "return false;". It
// will not submit the form. If you're not using return false
// and want the form to be submitted remove the line below
e.preventDefault();
// Now diable any submit button
$('input[type=submit], button[type=submit]').attr('disabled, 'disabled');
});
});
</script>

JavaScript work before submitting ASP.NET MVC form

I have an ASP.NET MVC view with a Beginform, that specifies an action and controller to hit on submit. But on submit I want to call a service using jQuery to get some data and then submit those data with the form.
Currently I have a submit button on the form where the onclick event of the button calls the JavaScript method. Depending of what result I get from the method I want the form to be submitted to the specified action.
Now I can't get this to work. Is it the right way to do this or should I instead make a post using jQuery? I think it would be nice to use what I have already specified as action/controller in the form.
I think the best way is to use event 'submit' on form, because users can want to submit form by pressing Enter in some fields. Guess, it is possible to change some input values during this event,
jQuery('form#myform').submit(function(e){
//....
if (somevar == false)
{
// stop submitting form
e.preventDefault();
}
else
{
jQuery('input#hiddeninput').val('somevalue');
}
})
The solution is add on submit event to form tag
onsubmit="return onSubmitClick(this);"
function onSubmitClick(item) {
console.log(item);
return false;
}
it's work well. GL ! HF !
I think it would be better to perform the task of querying an external web service in a controller action. This way you would always submit the form to the same controller action which will query the service and based on the results would either render a view or redirect to some other action.

Categories