I have the following script, which works perfectly BUT the problem is I need a form action attribute for it to work, thus my question how can I modify my current script that it prevents default form submit behaviour and submits form on current page without the need for an action attribute in form
$(function() {
var form = $('#editRes');
var formMessages = $('#formMsg');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//do the validation here
if (!validateLog()) {
return;
}
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
$(formMessages).html(messageHtml); // < html()
});
});
function validateLog() {
var valid = true;
//VALIDATE HERE
return valid;
}
})
In your ajax, you are using url: $(form).attr('action'). This means the form will get submitted to whatever is the action attribute of your form. Since there is none, the ajax will not work.
If you want the form to be without an action tag, you can just write the form submit url (page.php) in the ajax url part
$.ajax({
type: 'POST',
url: 'page.php',
data: formData,
...
...
});
Another option is to window.location.href.
Side-note: You do not need to rewrap form in $() as it is already a jQuery object in your second line -- same goes for formMessages.
$(function() {
var form = $('#editRes'); // this is a jQuery object
var formMessages = $('#formMsg'); // this is also a jQuery object
// Set up an event listener for the contact form.
form.submit(function (e) {
// Stop the browser from submitting the form.
e.preventDefault();
// do the validation here
if (!validateLog()) {
return;
}
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: window.location.href,
data: form.serialize()
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
formMessages.removeClass('error').addClass('success');
// Set the message text.
formMessages.html(response); // < html();
// Clear the form.
$('').val('')
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
formMessages.removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
formMessages.html(messageHtml); // < html()
});
});
function validateLog() {
var valid = true;
//VALIDATE HERE
return valid;
}
});
At the end of your submit function add:
return false;
This will prevent to browser from navigating away.
Related
I have an email sign-up form on a website.
The form appears in two areas of each web page: the header and the footer
It's the same exact form, just available on the top and bottom of the page for better UX and accessibility.
The form uses a jQuery/AJAX script to provide success and error responses to the user. (i.e., "Success! Your subscription is complete." and "Error. Please review and re-submit")
The problem I'm having is that the header form processes but the footer form does not.
Any ideas what's wrong with this code? Thanks.
P.S. The form was working perfectly when the header and footer forms each had their own script. The problem started when the scripts were consolidated into one file. I've posted the original scripts at the bottom. Also, nothing has been changed in the PHP, so I don't think the problem is there.
$(function() {
// get the forms
var form = $('#header-form, #footer-form');
// set up event listener
$(form).submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(form).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form
$('input').val('');
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- simplified HTML -->
<form action="form_processing.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<button type="submit" id="header-form-submit">Submit</button>
<div id="header-form-responses"></div>
</form>
<form action="form_processing.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<button type="submit" id="footer-form-submit">Submit</button>
<div id="footer-form-responses"></div>
</form>
Here's the original header code (works perfectly):
$(function() {
var form = $('#header-form');
var formResponses = $('#header-form-responses');
var submitButton = $("#header-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Your subscription is complete. Thank you!');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Here's the original footer code (works perfectly):
$(function() {
var form = $('#footer-form');
var formResponses = $('#footer-form-responses');
var submitButton = $("#footer-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Subscription complete.');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Within the $(form).submit( you're still using $(form), eg
var formData = $(form).serialize();
as form = $('#header-form, #footer-form') any call to $(form) (or just form) will affect/apply to/read from both forms. This depends on what the call is, eg form.attr("action") will always get the action from the first form.
Within the handler, change all $(form) (or just form) to $(this):
var formData = $(this).serialize();
...
url: $(this).attr('action'),
be careful using this inside a callback, so if you do need the relevant form then instead, change to
$('#header-form, #footer-form').submit(function(e) {
var form = $(this);
and continue to use form.
Note that in your code form is already a jquery object, but jquery allows you to "double wrap" - ie $(form) is the same as $($(form))
I recommend you remove the outer form variable completely, ie change to
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
which will help to remove the issue of using form not meaning this form.
Sorry I am a beginner with jQuery and Javascript. I want to be able to get the results into my modal from any form on the page that has class ajax. My code is below but not working correctly. Currently it opens the post result in a new page and not in the modal. Can anyone shed any light on my code?
Many thanks
$(document).ready(function() {
$('.ajax').click(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('name').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(value);
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
This probably happens because your browser submits the form by default. It doesnt know youre doing AJAX stuff. To prevent this, use preventDefault().
In addition to that, jQuery has a built in function for serializing (1 and 2) form data.
$(document).ready(function() {
$('form.ajax').click(function(event) {
event.preventDefault(); // prevents opening the form action url
var $form = $(this),
url = $form.attr('action'),
type = $form.attr('method'),
data = $form.serialize();
// console.log(value); // value doesnt exist outside of your loop btw
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
Also, its not quite clear if you bind the click event handler to a form or a button, I guess the first one. You should change the handler to the following:
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {
I have been trying to solve a simple but, for me, really hard problem.
I have a form and I need to add data from the form to a database, but with form validation. For validation I use the parsley plugin and for some input fields I use select2 plugin.
I try to add form in this way (Comments is in code):
//try to see is zemljiste or vrsta_rada = null to do not add data to database
var zemljiste = $("#parcele").select2("data");
var vrsta_rada = $("#vrsta_rada").select2("data");
//Now when I click on #dodaj I need to chech is zemljiste or vrsta_rada == null to do not start function for adding data but DONT work
$("#dodaj").click(function () {
if (zemljiste == null || vrsta_rada == null) {
alert('PLEASE fill the fields');
} else {
//HERE if zemljiste and vrsta_rada != null start validation and this also dont work
$('#myForm').parsley().subscribe('parsley:form:validate', function (formInstance) {
formInstance.submitEvent.preventDefault(); //stops normal form submit
if (formInstance.isValid() == true) { // check if form valid or not
zemljiste = $("#parcele").select2("data").naziv;
id_parcele = $("#parcele").select2("data").id;
vrsta_rada = $("#vrsta_rada").select2("data").text;
//code for ajax event here
//Here is ajax and when I fill all fields I add data to database but here success and error into ajax dont work???
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: {
naziv: $("#naziv").val(),
parcele: zemljiste,
vrsta_rada: vrsta_rada,
opis: $("#opis").val(),
pocetak: $("#pocetak").val(),
zavrsetak: $("#zavrsetak").val(),
status: $("#status").val(),
id_parcele: id_parcele,
}, //your form data to post goes here as a json object
dataType: "json",
success: function (data) {
//SO if success I add data but this code below dont work also in error dont work
$('#myModal').modal('hide');
drawVisualization();
console.log('YESSSSSSS');
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
});
}
});
With this, I have a few problems...
1. When submit code, the page refreshes and I don't want to do that.
2.When I fill in all the fields, I add data to the database but also add all the previous attempts with incorrect information. Why?
3. Why can I not see what return my success and error into .ajax in console.log ???
Look the pictures:
I have a form that, when submitted, goes through the usual e.preventDefault() and sends an ajax request instead. However, if this ajax request returns a certain condition, I want the form to be submitted normally. How do I achieve this?
// Submit handler
$(".reserveer_form").submit(function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(data) {
if($(".messagered",data).length > 0){
var errors = $(".messagered",data);
$(".gegevens").before(errors);
} else {
// SUBMIT THE FORM!
}
}
});
})
Invoke the native submit method on the form, so that it doesn't trigger the jQuery handler.
$.ajax({
context: this, // <-- set the context.
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
if ($(".messagered", data).length > 0) {
var errors = $(".messagered", data);
$(".gegevens").before(errors);
} else {
this.submit(); // <-- submit the form
}
}
});
Since your comment says you change a form variable, you could start your submit handler by checking that same form variable. If it is changed, just return true. If not, continue with the current handler.
You can use the submit() method or forms:
$(".reserveer_form").submit(function(event){
event.preventDefault();
var form = this,
$form = $(form);
$.ajax({
url: $form.attr("action"),
data: $form.serialize(),
success: function(data) {
var errors = $(".messagered", data);
if (errors.length > 0){
$(".gegevens").before(errors);
} else {
form.submit();
}
}
});
})
However, this seems to be a strange ajax request. First, you send the form (serialized, via ajax) to the server, and when the response contains no errors you send it again? The server would process it twice (and act twice, depending on your form). Also, the user does not get a message that his input is already processed - he clicks "submit", and it always takes a time until it is visibly submitted (where he even could change some input).
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}