Contact form using e.preventDefault(); not working live - javascript

UPDATE - the contact form is found at this URL.
I am trying to get the following contact form to function, using this tutorial.
I manage to get everything to work as expected on my computer using apache webserver.
After uploading the files to an online website, the ajax function does not kick in.
I seems like the e.preventDefault(); stops working after the upload, and the form is redirected to a new site,and not just being processed on the site without the reload.
I have also been trying to use the return false; instead of e.preventDefault(); without any success.
Her is my code:
.html
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
Please help!

That's because your JS is missing a closing });. Please check this demo to confirm that the default action is indeed prevented and the ajax does kick in. However, I was expecting a POST but instead I am seeing an OPTIONS request.
NOTE: Giving an element a name or id attribute value of submit is bad practice. You cannot for example use JavaScript to submit the form via default form submission -- this.submit() or $('form')[0].submit() without getting the error ...submit() is not a function .....
$(function() {
$('form').submit(function(e) {
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$("#loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$("#loading").fadeOut(function() {
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
});
}); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>

Since you are submitting via AJAX anyway, you may find it easier to change your input type to button, and bind to click instead of form submit, to avoid the default submit behaviour you are trying to circumvent.

Related

AJAX form only allows one submission?

I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?
How do i accomplish the form and script so I do not have to refresh?
Here is the form:
<form role="form" class="form-horizontal validate" name="create_form" id="create_form">
<div class="form-group">
<label class="col-sm-2 control-label" for="name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
</div>
</div>
<div class="form-group-separator"></div>
<div class="form-group">
<button id="submit_btn" class="btn btn-success">Create</button>
<button type="reset" class="btn btn-white">Reset</button>
</div>
</form>
And here is the AJAX part:
$(document).ready(function(){
$("#submit_btn").on("click", function () {
$.ajax({
type: 'POST',
url: 'data/create.php',
cache: false,
data: $('#create_form').serialize()
})
.done(function(data){
$("#name").val("");
})
.fail(function() {
console.log("ERROR");
});
// Prevent refreshing the whole page page
return false;
});
});
Hoping for help and thanks in advance :-)
use submit instead of click.
$('#submit_btn').on('submit', function(e) {
e.preventDefault();
... //rest of the code
});
I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>

Stop form from redirecting on submit

I'm very aware that this question has been asked several times but I have tried at least 6 solutions and it has not worked. I'm collecting data to send to a google form but on form submission the browser redirects to a success page. I'd like for it to all happen using AJAX but my code isn't working.
HTML:
<form id="userinfo" method="get" action="https://script.google.com/macros/s/xxx/exec" accept-charset="UTF-8" onsubmit="return false">
<input type="text" name="name" id="formname" placeholder="Name">
<input type="text" name="email" id="formemail" placeholder="Email">placeholder="Game Days">
<input type="submit" value="submit" id="upload_data"/>
</form>
JS:
$("#userinfo").submit(function(e) {
var urll = "https://script.google.com/macros/s/xxx/exec"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urll,
data: $("#userinfo").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
You could use the jQuery Form Plugin to send the form without doing a submit.
Your code should look kinda like this:
$("#userInfo").ajaxSubmit({
success: function(data)
{
alert(data); // show response from the php script.
}
});

Ajax show form after submit

i'm currently using the following ajax code to submit my form:
<script>
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.post('ajaxdmsgsub.php', $(this).serialize() )
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
</script>
form:
<div id="form-content">
<form method="post" id="reg-form" autocomplete="off" action="ajaxdmsgsform.php">
<label>Message</label>
<textarea class="txtarea" name="message"></textarea>
<div class="cleared"></div>
<input type="submit" value="Submit Message" class="submitit" onclick="hide('myModal')">
</form>
</div>
after submit my form disappears, I want the form to reset so users can keep submitting without a refresh - i'm using this function like an instant messenger. but have no idea how to keep the form from disappearing.
$('#form-content').fadeOut('slow', function(){
$('#form-content textarea, #form-content input').each(function(){
$(this).val("");
})
$('#form-content').fadeIn('slow');
});

Submit Form With Both Action and Onsubmit Function

My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">

AJAX HTTP post request is triggered 3 times

In my webapp, the Ajax request is executed 3 times, and I have no idea why this is happening.
Can someone please help here?
My Javascript:
$(document).ready(function() {
console.log("ready!");
$('form').on('submit', function(e) { //
e.preventDefault();
// on form submission ...
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'first': valueOne,'second': valueTwo,'third': valueThree},
success: function(data) {
var res = data.AVG;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p);
},
error: function(error) {
console.log(error)
}
});
}); });
And my HTML is:
<form role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="text" class="input-medium" id="perfid" name="perfid" placeholder="Enter a Perf ID" required style="height:30px;">
<input type="text" class="input-medium" id="hostname" name="hostname" placeholder="Enter a HostName" style="height:30px;">
<input type="text" class="input-medium" id="iteration" name="iteration" placeholder="Enter a Iteration" required style="height:30px;">
<button type="submit" class="btn btn-default" style="height:30px;">Get Data</button>
</div>
</form>
I have written the code for only one AJAX POST request,
EDIT:
This is the console output:
Please make sure you have included the js file only once,
and add a return false at the end of the submit event callback
look at the selector
$('form').on('submit', function(e) {
if the page has 3 forms, the above selector will execute 3 times
Try to add id to the form like this. sorry about my bad english

Categories