Script not executed when submitting form - javascript

I have a form and want to send the form data to a PHP file using Ajax:
This is my form:
<div class="acc_content clearfix">
<form name="contactForm" id="contactForm" class="nobottommargin" action="guarda_pass.php" method="post" >
<div class="col_full" style="color: #898989">
<label style="color: #898989" for="login-form-username">Escribe tu nueva contraseƱa:</label>
<input type="text" id="password" name="password" value="" class="form-control" required />
</div>
<div class="col_full" style="color: #898989">
<label style="color: #898989" for="login-form-username">Confirma tu nueva contraseƱa:</label>
<input type="text" id="con_password" name="con_password" value="" class="form-control" required/>
</div>
<div class="col_full nobottommargin">
<button class="button button-3d button-black nomargin" style="background-color: #6fb6e5" type= "submit" value="login">Registrar</button>
</div>
</form>
<div id="contactResponse"></div>
</div>
And this is the script:
<script src="js/jquery.js"></script>
<script>
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
password_value = $form.find( 'input[name="password"]' ).val(),
con_password_value = $form.find( 'input[name="con_password"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
password: password_value,
con_password: con_password_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
After clicking the submit button, the page reloads itself and the script is not executed.
What am I doing wrong?

Your code seems to work.
This jsfiddle shows it (I have commented out the $.post ajax call and added an alert to demonstrate this).
Maybe you included the script in a place where it is not executed or maybe it gets executed too early -- before the DOM becomes available.
You can circumvent the latter by wrapping your script into:
$(function() {
// your script content with $("#contactForm")... here
});
See .ready() on api.jquery.com for more details about this.

Related

Show loading GIF when submitting form

I have form which has some inputs. I would like to show loading gif while submitting the form and hide when form is submitted.
I sent details using php and once submitted it shows response, but when submitting form, I would like to show gif as loading screen and hide when it is completed.
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// 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');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#subject').val('');
$('#message').val('');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" id="name" name="name" value="Sagar Rawal" required>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter Email" id="email" value="searchbbc1881#gmail.com" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Message" id="message" name="message" required>This is message </textarea>
</div>
<button type="submit" name="submit" class="mu-send-msg-btn"><span>SUBMIT</span></button>
</form>
Okay, first of all you could use modal and add gif file on top of it. Or you can simply add the image where you want to add. Here, I will work with modal.
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
var result = $.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
});
// Here, you have to add, what you want to do right after data is sent.
$("#modal").css("display", "flex");
// Overflow of main body to hidden
$("body").css("overflow", "hidden");
result.done(function(response) {
// Now, you can hide modal or loading gif
$("#modal").css("display", "none");
// Overflow of main body to hidden
$("body").css("overflow", "auto");
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Reset form at once instead
$("#ajax-contact").reset();
});
});
});
#modal {
display: none;
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.6);
justify-content: center;
align-items: center;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" id="name" name="name" value="Sagar Rawal" required>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter Email" id="email" value="searchbbc1881#gmail.com" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Message" id="message" name="message" required>This is message </textarea>
</div>
<button type="submit" name="submit" class="mu-send-msg-btn"><span>SUBMIT</span></button>
</form>
<!-- My modal for modal -->
<div id="modal">
<img width=200 src="https://thumbs.gfycat.com/BogusEmptyBrontosaurus-small.gif" alt="Loading-gif"/>
</div>
In js, I have added result as object of ajax. And, right after data are sent, we show our gif file. And, after we gave got data, we will again hide gif div. Feel free to ask!!!!!!!!

How to prevent page from reloading after form submit - JQuery

I am working on a website for my app development class and I have the weirdest issue.
I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submitting the form, and I cannot or the life of me figure out how to make the JQuery go on in just the background. That is sorta of the point of using JQuery in the first place haha. Anyways, I will submit all relevant code, let me know if you need anything else.
<script type="text/JavaScript">
$(document).ready(function () {
$('#button').click(function () {
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
</script>
<div class= "main col-xs-9 well">
<h2 style="color: black" class="featurette-heading">Join our mailing list!</h2>
<form id="main" method = "post" class="form-inline">
<label for="inlineFormInput">Name</label>
<input type="text" id="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<label for="inlineFormInputGroup">Email</label>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<input type="text" id="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe#email.com">
</div>
<!--Plan to write success message here -->
<label id="success_message"style="color: darkred"></label>
<button id ="button" type="submit" value="send" class="btn btn-primary">Submit</button>
</form>
This is my php if its relevant:
<?php
include 'connection.php';
$Name = $_POST['name'];
$Email = $_POST['email'];
//Send Scores from Player 1 to Database
$save1 = "INSERT INTO `contact_list` (`name`, `email`) VALUES ('$Name', '$Email')";
$success = $mysqli->query($save1);
if (!$success) {
die("Couldn't enter data: ".$mysqli->error);
echo "unsuccessfully";
}
echo "successfully";
?>
This is a screenshot of the log:
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
Use <button type="button"> to override default submission behavior
Use event.preventDefault() in the onSubmit event to prevent form submission
Solution 1:
Advantage: simple change to markup
Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?
Insert extra type attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Solution 2:
Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Better variant:
In this improvement, we listen to the submit event emitted from the <form> element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:
The name attribute is required for .serialize() to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe#email.com">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
clear the previous state when loading the page.... add this to document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Ajax 405 (Method Not Allowed) when I action field is blank or same as current page

First off thanks to #abc123 for the code below as I found this on one of his posts.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('posting');
});
});
</script>
</body>
</html>
I have made a slight amend as I want to submit the form to the page on which it sits, but when I do, I get 405 (Method Not Allowed) when I look in Developer Tools. I know this is because the action="" is null, but is there a way round this?
The url variable is empty. Try replace line url = $form.attr( 'action' );
with
url = $form.attr('action') == '' ? window.location : $form.attr('action');

Ajax form - still cannot get it working with validation

I've posted on here previously, however, the answers received were of no help as they did not work.
I have a form that is using AJAX but the error or success messages don't appear.
Can anyone see what I may have overlooked? Thanks.
HTML
<form id="newsletter" action="http://app.bronto.com/public/webform/process/" method="post">
<input type="hidden" name="fid" value="gmy3v1ej883x2lffibqv869a2e3j9" />
<input type="hidden" name="sid" value="37ea72cebcc05140e157208f6435c81b" />
<input type="hidden" name="delid" value="" />
<input type="hidden" name="subid" value="" />
<script type="text/javascript">
var fieldMaps = {};
</script>
<label for="nameField">Name:</label>
<input id="nameField" type="text" id="field_66663" name="39829[66663]" value="" />
<label for="emailField">Email:</label>
<input id="emailField" type="text" name="39821" value="" />
<input type="submit" value="Submit" />
<div id="newsletter-message" style="display:none;"></div>
</form>
JS
//ajax subscribe
$(document).ready(function(){
$("#newsletter").submit(function(event) {
event.preventDefault();
alert("submitting");
alert(data); //it doesn't alert here??
console.log($("#newsletter").serialize());
$.post($("#newsletter").attr("action"), $("#newsletter").serialize(), function(data){
alert(data); //doesn't alert here either
if(data == 'success'){
$('#newsletter-message').html('You have been signed up.').removeClass('error').css('visibility','visible');
} else {
$('#newsletter-message').html('Please complete the fields and re-submit').addClass('error').css('visibility','visible');
}
});
//Stop the normal POST
return false;
});
});
EDIT
I've now tried this but still no luck..
$("#newsletter").submit(function(event) {
event.preventDefault();
var $form = $( this ),
ufname = $form.find( 'input[name="39829[66663]"]' ).val(),
uemail = $form.find( 'input[name="39821"]' ).val(),
url = $form.attr( 'action' );
var posting = $.post( url, { name: ufname, email: uemail } );
posting.done(function( data ) {
$('#newsletter-message').html('You have been signed up.').removeClass('error').css('visibility','visible');
});
});
The visibility and display are 2 different things in CSS.
You are creating your display div with display:none;, but then you try to make it visible with .css('visibility','visible');, so you just end up with:
<div style="display: none; visibility: visible;" id="newsletter-message">...</div>
Which is still not visible because of the display:none;.
You should replace the actions in your if by:
if(data == 'success'){
$('#newsletter-message').html('You have been signed up.').removeClass('error').show();
} else {
$('#newsletter-message').html('Please complete the fields and re-submit').addClass('error').show();
}
Here is the documentation about the .show() jQuery function: http://api.jquery.com/show/
Small thing i noticed, you are using 2 id attribute for name field which makes your input invalid and may cause the problem.
<input id="nameField" type="text" id="field_66663" name="39829[66663]" value="" />
Also do as #Thierry said and avoid using numbers in name field if possible.

Using jquery.validate to validate submitted form based on which form is used

I currently have two forms on a page, an update form and an add form, what I want to do is on submission of either form, pull the id of that form, along with the action, validate the particular form, then load the return from the webserver.
I got it to work by specifically using each form's id, but the js code is repeated twice, id prefer it to be a bit more dynamic.
<script src="assets/js/jquery-1.8.2.js"></script>
<script src="assets/js/bootstrap.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<div id="myTabContent" class="tab-content">
<div class="tab-pane active" id="update">
<form action="php/update_level.php" method="post" id="form1">
<h2>Update Level</h2>
<label>Select Bag Level</label>
<select id="target" name="levelSelect"> <option selected>Select</option>
<?php
foreach($result as $row)
{?>
<option><?php echo $row['Level'] ?></option>
<?php
}
?>
</select>
<div id="upForm">
</div>
<div class="message">
</div>
</form>
</div>
<div class="tab-pane" id="addNew">
<form action="php/add_level.php" id="form2">
<h2>New Level</h2>
<label>Level</label>
<input class="required" maxlength="10" minlenght="1" type="text" name="level" placeholder="Level">
<label>Description</label>
<textarea class="required" name="description" rows="3" placeholder="Description of level type"></textarea>
</br>
<div class="message">
</div>
<div class="form-actions">
<button id="inFormSub" type="submit" class="btn btn-large btn-primary">Submit</button>
</div>
</form>
</div>
</div>
JS:
$('form').submit(function(e){
e.preventDefault();
var id=$(this).attr('id');
var action=$(this).attr('action');
console.log(action + ' ' + id); //works outputs update_bag.php form1 on submit of form1
//add_bag.php form2 on submit of form2
$(id).validate({
submitHandler: function() {
console.log(action + ' ' + id); //doesnt work
$(id).find('div.message').load(action, $(id).serializeArray());
}
});
JS that works
$('#form1').validate({
submitHandler: function() {
var action = $('#form1').attr('action');
console.log(action + ' validate1');
$('#form2').find('div.message').load(action, $('#form1').serializeArray());
}
});
$('#form2').validate({
submitHandler: function() {
var action = $('#form2').attr('action');
console.log(action + ' validate2');
$('#form2').find('div.message').load(action, $('#form2').serializeArray());
}
});
My knowledge of JS and Jquery is small at best, and im probably staring the solution right in the face
A common approach to applying a plugin that requires specific data per element is to loop over the elements using each() so you can access this within the loop in order to easily access the individual form element without duplicating the code for each one
$('#form1,#form2').each(function() {
var $form = $(this);
var action = $form.attr('action');
$form.validate({
submitHandler: function() {
$form.find('div.message').load(action, $form.serializeArray());
}
});
});
You can use on submitHandler the form variable and get the id and action
...
submitHandler: function(form){
console.log($(form).attr('id'), $(form).attr('action'));
...
}
the $(this).attr("id") call just returns the ID of the element, but that is not a propper css selector, so you need to add the hash sign youre self
try and change the call to:
$("#"+id).validate({
//validate code here
})

Categories

Resources