I'm having trouble understanding what the form action is used for. It seems like I can handle form data with a Javascript function by setting the onsubmit value to that function. I'm seeing a lot of different examples online that are confusing me even more.
Can someone walk me through what this will do and maybe give me an example of what the form action could do that "onsubmit" can't or shouldn't?
<form onsubmit="someFunction()" action="???"> ... </form>
A user will enter information into the form, then they hit a button to "submit" that information. someFunction() will do stuff with that information... then, the form action is responsible for what? I've seen some examples that look like it just specifies a URL to a page telling the user something like "Thanks for submitting".
I'm sorry if this is confusing. I'm not sure how to ask what I'm confused about. I'm looking for a really simple answer that you might give to a child about what that line of code means for the user and also for the information that was entered into the form.
The difference here is subtle but important:
onsubmit is an event attribute, meaning whatever JS is in it will be called on the submit event.
action tells the browser where to send the contents of the form when it is submitted in either a GET or POST request (POST by default, unless specified otherwise by the method attribute), then reloads the page with the result of the request it sent.
The action attribute is less customizable because it won't run any of your custom JavaScript, all it will do is send the data to your backend. On the other hand, onsubmit runs your custom JavaScript, which can do whatever you want (including sending data to your backend). If all you need to do is run some client-side JavaScript when the form submits, use onsubmit. If all you need to do send data to the server when a form submits, use action.
Generally, you don't want to use both at the same time because if action sends data to your backend, then your page will reload. In fact, even if you don't specify an action attribute, then the page will still reload because it is the default behavior. When using the onsubmit attribute to run JavaScript when a form is submitted, you'll need to override this default behavior with event.preventDefault(), hence why most onsubmit handlers look like this:
function onsubmitHandler(event) {
event.preventDefault()
// ... rest of the code ...
}
onsubmit() function needed to handle the form submit in JavaScript. When we add the URL in action attribute, we can't handle the form data in JavaScript. In this case, we can't validate the form data, so the empty data is sent to the server. This will increase server load and it's really bad.
Related
So currently, I have a form with many parameters and a button that when clicked causes the user inputs to be edited into a more manageable string. Is it possible to at the same time send it to my Nodejs server and if so how to get that value (I'm guessing something like req.body.generateForm but I doubt that works)? This is the basic structure of my form.
<form id="generateForm" method="post" action="/app" onsubmit="return writeForm(event);">
Yes, instead of attaching your function directly on the form via onsubmit and calling it. You can instead add an event listener and prevent default.
adding event listener
let form = document.querySelector("#generateForm");
form.addEventListener("submit", writeForm, true);
more about event listenders here:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
function writeForm(event){
event.preventDefault();
//your function to mutate and send data here...
}
i advise you practise sending data using vanilla javascript once, just to know how it works. then using ajax Jquery to make it easier. lastly moving forward using a webframework to really simplifly things.
FYI, i found MDN web docs to be a great resource.
I want to intercept my form's submit response via javascript. Submit is normally done by a submit button or jquery's .submit() (with no params). Is there a way to intercept that submit response like;
.submit().done(callback)
I know .submit() does not have support for this, however creating a post request like finding every input in that form and getting their values into data object which we will then pass to .post() method seems a bit clumsy to me. Besides there will be no advantage of using <form> tags in html in that approach.
Any suggestions for this?
No, you can't.
Besides, when you do .submit() or click submit button, the page unloads and a new page loads. which means all java script on the page is gone so there is no point in having a callback.
I have a submit input in a form with an onclick method. The onclick method correctly adjusts the action of the form and allows the form to submit (submission is handled naturally, not through a javascript submit). What I need to do is add a http request header (X-Requested-With = XMLHttpRequest to be exact). Is there a way to ensure the form post is sent with that header? The post cannot be submitted via javascript using the form.submit() method.
According to this answer what you're asking for is impossible in its current form. However you could modify where the form submits too. For example POST to:
www.mysite.com/XMLHttpRequest or www.mysite.com/NormalRequest
so that the server understands the context of the request.
I have a popup which asks the user for login information, which means two input text fields for password and username.
Now as I will be verifying the information using ajax I didn't wrap the elements on a because form always needs a php action, correct? or am I missing something?
So I'd like to know if there is a fancier way to check if the user pressed enter, in order to submit the login information, than checking each time a key is pressed, with keydown, if it's the enter key.
Thanks in advance
You still need a form to wrap your user inputs, and that form still has an action. However, you won't do a full page post. Instead, you'll send an AJAX post. jQuery makes this really easy.
$(function() {
$("#myForm").submit(function () {
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url, data);
return false;
});
});
Now as I will be verifying the information using ajax I didn't wrap the elements on a because form always needs a php action, correct? or am I missing something?
A form requires an action, it doesn't have to point to a URL that is processed by PHP. There are much nicer languages available (this is subjective).
What you are missing, is a fallback for when the JavaScript isn't run for some reason (such as the file not being downloaded due to a network glitch, the client not supporting JS or having JS, etc). Build on things that work.
So I'd like to know if there is a fancier way to check if the user pressed enter, in order to submit the login information, than checking each time a key is pressed, with keydown, if it's the enter key.
If you build on things that work, then you'll have a form anyway, and can run your JS in the submit handler. Then you don't need to care if the form was submitted by a keypress or a button click.
Add attribute to form
<form onSubmit="call your javascript; return false;"> ...
so when enter, or submit button is pressed your javascript will be called and then you can do what ever you want with your form values. Reutrn false will prevent classic form submit.
I hope this helps
I have a race condition in which I do not want an AJAX call to occur, if a form on the page is currently submitting.
I'd rather not alter the code for the form.
I was thinking of attaching event handlers to each of the form elements so that onsubmit it would increment a counter and then on onreadystatechange decrement the counter.
Then before the AJAX call, check to ensure the counter is zero before firing.
However is there an easier way such as (pseudo code):
form.isSubmitting
EDIT:
The race condition is not because of the JavaScript per-say. It is caused by what happens on the server side on response of the ordering of these actions.
To give you an idea of the broader problem:
A cookie is set when the form post returns.
On the AJAX call (needs to happen every X seconds)... the server-side (if the form post has happened) expects the cookie to be set.
Sometimes....
If there is a delay in the form submission returning (and setting the cookie client side), the AJAX call is triggered without sending the cookie back.
The server expects the cookie, because as far as it is concerned the form post has been successful.
However it is the client side I need to control to ensure the actions are performed in a prescribed way.
So correct JavaScript itself cannot cause race conditions, but (as far as my testing has shown) - the submission and returning of POST/AJAX calls causes a race condition in my particular case.
There are no "race conditions" in Javascript on a web page, because there's just one thread of execution. If you want to prevent event handlers from doing anything after a form has been submitted (or at any time, really), the very simplest thing to do is set some globally-accessible flag. The handler routines just have to check for that. Of course it's important that the flag is cleared when appropriate.
edit — OK after your edit, it's a little more clear what you're doing, but one thing is not clear: how exactly is the form being posted? Is it a "natural" form post? If that's the case, the whole page is going to be reloaded by the response. Is the target a separate <iframe> perhaps?
Or is the form being submitted by some other AJAX code?
If the form is being submitted "naturally" by the browser, and we're talking about a whole page being reloaded, then that's probably the simplest case. The form's "submit" handler should simply set the global flag, and the code running via the interval timer should just do nothing on the intervals when the flag is set. There's no need to worry about clearing the flag, because the page is going to blasted by the response anyway.
If the form is posting within an <iframe> on the page, or posting to a hidden <iframe>, then it's almost the same as (1) except that the response page will need to clear the global flag. Exactly how to do that depends on what the application setup involves, but basically it'll just be some Javascript in the response that sets top.postingFlag to false (or whatever).
If it's separate AJAX code that's posting the form, then you'd set the flag when you start the XMLHttpRequest, and clear it in the handler(s) for success/failure.
In all cases, the key is for code in the interval timer to watch for the state of the flag, and avoid posting when the flag is set.
You can add this to the form tag:
<form ... onsubmit="this.setAttribute('isSubmitting', 'true');">
And you'll be able to see if it's "submitting" by checking that attribute.
Yes, that would work.
You can submit the form via an AJAX call. That way you can control the ajaxSend and the ajaxComplete events and have a global variable say var formIsSubmiting = false serving as a flag.
Right before the non-form AJAX call check the status of the variable and that should prevent your race condition.