I need to call javascript ajax function after successful dynamically created form submit.
Or how to check the form was successfully submitted or not using java script .
Here's how to check if the form was submitted and also an example of how to handle a callback:
var form = document.querySelector('form');
var handleSubmit = function (e) {
// remove the preventDefault
// added just to demonstrate the value is true
// without proceeding with submittion and pg refresh
e.preventDefault()
form.setAttribute('data-submitted', true)
console.log(form.getAttribute('data-submitted'))
handleAjaxCall()
}
var handleAjaxCall = function () {
console.log('ajax call here!')
}
form.addEventListener('submit', handleSubmit, false)
<form data-submitted="0">
<button type="submit">submit</button>
</form>
Related
I need to add some data to a form using FormData so that when the form is submitted this new piece of data is also posted, but I can't get it working. Note that I do not want to use ajax or fetch to send formData since I want the page to redirect user to a different page when he clicks the submit button.
const myForm = document.querySelector('form');
myForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(myForm);
formData.append('age', '20');
event.target.submit();
});
As mentioned in comments the best way to do this was to prevent the normal event, submit your own formData object and then redirect by yourself.
var form = document.querySelector("form");
form.addEventListener('submit', e => {
e.preventDefault()
// build up formdata
const formData = new FormData(form);
formData.append("age", '20');
const request = new XMLHttpRequest();
request.open("POST", "submitform.php");
// redirect on success
request.addEventListener('load', function( event ) {
window.location.replace('/my-locaiton')
});
// Do whatever needed on error
request.addEventListener('error', function( event ) {
console.log('failed request..')
});
request.send(formData);
})
<form id="form" action="POST" target="redirect.html">
<input type="text" value="somtext">
<input type="submit">
</form>
If you still want to let the form do the job you could do something like this to prevent the event and then dispatch it again..
You would need to add hidden elements to the form in this case:
const form = document.getElementById('form')
const listener = async (e) => {
// prevent default action.
e.preventDefault()
// only run the listener only once.
form.removeListener('submit', listener)
// append actual data..
const ageInput = document.createElement('input')
ageInput.style.visibility = 'hidden'
ageInput.setAttribute('name', 'age')
ageInput.setAttribute('value', '20')
form.appendChild(ageInput)
// dispatch event again!
e.target.dispatchEvent(e)
}
form.addEventListener('submit', listener)
After validating my form with javascript I can not get it to submit to the server
myForm.addEventListener("submit", validation);
function validation(e) {
let data = {};
e.preventDefault();
errors.forEach(function(item) {
item.classList.add("cart__hide");
});
at the end of the validation I have the following code
if (!error) {
myForm.submit();
}
I also tried
if (error = false) {
myForm.submit();
}
if ((error == false)) {
myForm.submit();
}
when I console log error I am getting all false so the form should submit.
I am getting the following console log error
TypeError: myForm.submit is not a function
I did this same validation on an html page and it worked fine. Now I am trying to get it to work on a PHP page and it will not submit.
I am not sure why the myForm.submit() is causing the error.
Thanks
Jon
Remove e.preventDefault(); from your code and put it in your validation function like this:
if (error) {
e.preventDefault();
}
What you need to do is to only call Event#preventDefault when there is an error.
myForm.addEventListener("submit", validation);
function validation(e) {
var error = !form.checkValidity(); // replace this with the actual validation
if (error) e.preventDefault();
}
<form>
<input type="text">
<input type="submit" value="submit">
</form>
This question already has answers here:
Form Submit Execute JavaScript Best Practice? [closed]
(3 answers)
Closed 11 months ago.
When I press the Submit button of a form it runs a php file which stores the answer to a db.
Is it possible to use the Submit button of a form to submit the user's choice and immediately after that run a function without further actions from the user?
For example, in the following simple form and php, how can I run a function when the user presses Submit?
<form action="db.php" method="post">
A:<input type="radio" name="answer" value="A">
B:<input type="radio" name="answer" value="B">
<input type="submit" name="submit value="submit">
</form>
<?php
$con = mysqli_connect('localhost','my user id','my password');
if(!con) {
echo 'not connected to server';
} else {
echo 'something else is wrong';
}
if(!mysqli_select_db($con,'my user id') {
echo 'Database error selection';
}
if (isset($_POST['submit'])) {
$answer=$_POST['answer'];
$sql = INSERT INTO test1 (columnName) VALUES ('$answer');
mysqli_query($con,$sql); // Execute query
}
?>
As an example let's take the following function which is a part of a larger file.
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
You can add an onsubmit event handler to the form
<form action="db.php" method="post" onsubmit="functionToCall()">
which will call the given function when the form is submitted. If you want to stop the form from being submitted, return false from the function. As #JokerDan said, you can also use AJAX within your function and omit the form action altogether.
function functionToCall() {
// Do something before you submit your form (save data locally or whatever)
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200) {
//Do something after submitting the form (if you want to change the page or redirect)
}
};
http.open('POST', 'db.php');
http.send(/*send post data here*/);
}
If you want to send data with the AJAX request, you will have to pull it from the form and put it in the http.send() line in the same format you pass data in the URL (data=answer&submit=true)
The proper way to do this, is to first select your form using something like document.querySelector or document.getElementById (only possible if the form element has an id).
var form = document.querySelector('[action="db.php"]');
After you selected your form, use the addEventListener of your form to add an evenListener.
form.addEventListener('submit', myListener, false);
Now you'll just need to create a function that looks like this :
function myListener(event) {
// DO STUFF
}
Here, event is an object of type Event that provides more information about the form you submitted. This function will be called every time you try to submit your form!
I am working on a jQuery validation "plugin" (not yet a plugin) that use my Zend_Form validators to verify the fields before submitting, client-side, so I only have to specify my constraints one time instead of two (Zend Validators + jQuery Validate Plugin, for example).
I store the validation AJAX requests for each field, then wait for them to finish, and then read the results and show or not an error message.
The problem : when I enter validated strings and hit submit, it shows no errors (good so far), but I have to re-click the submit button the form to really submit it.
Making a return true or false inside the .whenAll function is ignored and does not work, that's why I used a flag to tell the function if yes or no it can really submit the form.
$(function() {
var form = $('form'); // target form
var requests = [], validations = []; // used to store async requests and their results
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs we want to check in the form
var cancelSubmit = true; // skip validation flag
form.submit(function( ) {
// if we call the submit inside the function, skip validation and do submit the form
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
this.submit();
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations
requests.length = 0;
validations.length = 0;
// for each input (text/password), storing the validation request
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
// response is formatted like this
// { valid: 1 } or { valid: 0, message:"This is the error message" }
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error and store result
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
validations.push(0);
}
// else, remove error (if there was) and store the result
else if(json.valid == 1) {
if($(formGroup).hasClass('has-error'))
{
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
}
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
// and if no error ("0") in the results, we resubmit the form with skip-flag
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.off('submit');
form.submit();
}
else
console.log('[-] There is still errors.');
}
});
});
});
// there are errors, so we won't submit the form
if(cancelSubmit === true)
return false;
});
});
Do you see a logic flaw in my code ? Maybe re-submitting the form with a flag isn't the right way to do it ?
You're returning from a sub scope rather than from the form submit handler. Instead, always prevent the submit, and then force it to submit with form[0].submit() when you want it to submit.
form.submit(function(e) {
e.preventDefault();
...
// now i want to submit...
form[0].submit();
form[0].submit() will bypass your jquery bound submit handler.
What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either
$('#submit').click(function() {
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return false; // cancel form submission if email invalid
}
return false; // return true if no errors once i get it working
});
Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
// now that document is "ready"
$('#formId').submit(function() {
var email = $('#emailInput').val();
alert(email);
if(email.indexOf("#") == -1){
alert("invalid!");
return false; // cancel form submission if email invalid
}
alert("valid!");
return true; // return true if no errors once i get it working
});
});
Try wrapping your code in a ready block.
$(document).ready(function(){
// your code here
});
You should also be using the submit event on the <form> element, I think.
This is going to work. If you don't understand why, feel free to ask :)
var validated = false;
$(document).ready(function(){
$("#rfq").submit(function(event) {
if (validated === true) {
return true;
}
event.preventDefault(); // prevent submission
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return;
}
validated = true;
return $(this).trigger('submit');
});
});
You could try using this function to validate your address.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
And then modify your code to submit the form.
$('#submit').click(function() {
var email = $('#email').val();
if(!validateEmail(email)){
$("#email").addClass('invalid');
}
else {
$("form").submit();
}
});