jQuery not recoqnizing form and page refreshes - javascript

I have a form that needs to be submitted and the data sent to mysql with Ajax and jQuery, however when clicking submit, the page refreshes and the jQuery code is not running.
Here is my HTML code:
<form class="form-horizontal" role="form" action="" method="post">
<input type="text" id="firstname" class="form-control" placeholder="Firstname" required=""></br>
<input type="text" id="lastname" class="form-control" placeholder="Lastname" required=""></br>
<input type="text" id="signup_email" class="form-control" placeholder="Email address" required=""></br>
<select id="gender" class="form-control">
<option>Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select></br>
<input type="password" id="signup_password" class="form-control" placeholder="Password" required="">
<input type="submit" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
</form>
And here is my jQuery:
<script type="text/javascript">
$(function()){
$("#signup_button").click(function() {
var firstname = $("input#firstname").val();
var lastname = $("input#lastname").val();
var email = $("input#signup_email").val();
var gender = $("select#gender").val();
var password = $("input#signup_password").val();
var datastring = 'new=yes'+'&firstname='+firstname+'&lastname='+lastname'&email='+email+'&gender='+gender+'&password='+password;
$.ajax({
type:"POST";
url:"api/signup.php";
data: datastring;
cache: true;
success: function(html) {
$.("#alert_succes_congrats").css('display', '');
}
})
return false;
})
}
</script>
Thank you.

You have two options to solve your problem:
1st option:
Change
<input type="submit" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
To
<input type="button" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
So the button will not trigger a form submit.
2nd option:
Put an event.preventDefault at your click handler.
$("#signup_button").click(function(event) {
/* Your stuff */
event.preventDefault();
}
So it will not trigger browser default action to form submit button.

You code has lot of syntax error:
$(function()){
Should be
$(function(){
Plus the ajax members should be separated by comma and not semi-colon, there was issue in string concatenation as well. Next time this happens, please check the browser console for any javascript issues.
This should work
<script type="text/javascript">
$(function(){
$("#signup_button").click(function() {
var firstname = $("input#firstname").val();
var lastname = $("input#lastname").val();
var email = $("input#signup_email").val();
var gender = $("select#gender").val();
var password = $("input#signup_password").val();
var datastring = 'new=yes'+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&gender='+gender+'&password='+password;
$.ajax({
type:"POST",
url:"api/signup.php",
data: datastring,
cache: true,
success: function(html) {
$("#alert_succes_congrats").css('display', '');
}
});
return false;
});
});

Related

HTML radio button always submits last option to PHP

No matter what option is chosen, this code will always submit the second option to PHP.
Here is my form:
<div class="modal">
<div class="modalContent">
<div class="modalHeader">
<p>Add an income / expense</p>
<span class="closeBtn" onclick="closeit()">×</span>
</div>
<form class="insertData" action="insert.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="category">Category</label>
<select name="category" required>
<option value="food">Food</option>
<option value="bills">Bills</option>
<option value="rent">Rent</option>
</select>
<label for="amount">Amount</label>
<div class="radios">
<input type="radio" name="ie" value="income"><p>Income</p>
<input type="radio" name="ie" value="expense"><p>Expense</p>
</div>
<input type="number" name="amount" required>
<label for="description">Description (optional)</label>
<textarea type="text" name="description"></textarea>
<input id="start" type="text" name="start" value="" required style="display:none;">
<input id="end" type="text" name="end" value="" required style="display:none;">
<input class='submitBtn' type="submit" name="" value="Submit">
</form>
</div>
</div>
Here is the PHP (just echoing for debugging purposes right now):
if (isset($_POST['name'])) {
echo htmlspecialchars($_POST['ie']);
}
The data is going in via AJAX here (using FullCalendar)
select: function (start, end) {
document.getElementsByClassName('modal')[0].style.display = 'block';
document.getElementById('start').value = $.fullCalendar.formatDate(start,
"Y-MM-DD HH:mm:ss");
document.getElementById('end').value = $.fullCalendar.formatDate(end,
"Y-MM-DD HH:mm:ss");
$('form.insertData').on('submit', 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;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});
},
No matter what option is chosen it will always submit 'expense'.
If I swap them around on the form then it will always submit 'income', so it seems to be always the last option is being submitted.
This error occurs because you loop all element has name attribute, and get the value. Including radio button. If you want to get selected radio button you must add if, for check if radio button has checked.
You can use code below, this code simpleer then you must check radio button:
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
$.ajax({
url: url,
type: type,
data: $('form.insertData').serialize(),
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});

Submitting form with ajax and formspree using VuesJS

I'm trying to submit a form using formspree I get two different errors. When I try to submit the form after I refresh the page I get an error on a new page saying
Cannot POST /Contact
When I go back and try to submit the form again I get an error in the console saying:
POST https://formspree.io/sheabathandbody#mail.com 400 () jquery.min.js:4
send # jquery.min.js:4
ajax # jquery.min.js:4
(anonymous) # main.js:8
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
I've used this method/code to submit my forms before so i don't know what the problem could be
Contact.vue form
<form id="contact" name="contact-form" method="post" action = "">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn" >Submit</button>
</fieldset>
</form>
Here's my main.js
(function($) {
$(window).on("load", function() {
// Contact form
var form = $("#contact");
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
})(jQuery);
Guess this has nothing to do with VueJS since it does not use at all vue in that chunks of code you shared, this is pure jQuery.
Said that, the problem sending the form was because you were not listening correctly to submit event.
form.on('submit', function () { ... })
On the other hand, ajax call is not working correctly; you should check documentation of formspree.io and correct it.
Check next code
$(document).ready(function() {
// Contact form
var form = $("#contact");
form.on('submit', function(event) {
alert('Hola hola. This is working now!');
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact" name="contact-form" method="post" action="">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" value="blah" required="required">
</fieldset>
<fieldset>
<input value="email#email.com" placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input value="123123123" placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required">Damn</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn">Submit</button>
</fieldset>
</form>
You can create a method for example postNow.
methods: {
postNow() {
const link = "https://formspree.io/sheabathandbody#mail.com"
var data = new FormData();
data.append('_replyto',this.email)
data.append('message',this.message)
this.axios.post(link,data , {
headers: {
'Accept': 'application/json',
},
// body: data,
}).then(res =>{
console.log("response ===" ,res)
this.email = "" ;this.message=""; //don't forget to create your data
}).catch(err =>{
console.log(err)
});
}
},
And in your template you can use the simple HTML form with few tweaks ofc,
<form #submit.prevent="postNow" method="POST" >
<label>
Your email:
<input type="email" name="_replyto" v-model="email" />
</label>
<label>
Your message:
<textarea name="message" v-model="message"></textarea>
</label>
<button type="submit">Send</button>
</form>

Submit form with ajax via callback

I want to submit the form when a gcapcha was clicked. I tried submit with (my silly) jquery function that I know. But it's not work.
Here is my code (what's wrong with it).
Javascript
var verifyCallback = function(e) {
document.getElementById("form-contact").submit();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(),
success : function(data){
$("#contact").html(data);
}
});
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};
HTML
<div id="contact" class="contact-form">
<form class="ajaxForm detailedsearch inline-style" method="post" id="form-contact">
<input type="text" class="form-control" name="cntc_name" placeholder="Your name" required>
<input type="email" class="form-control" name="cntc_email" placeholder="Your email" required>
<input type="text" class="form-control" name="cntc_tel" placeholder="Your phone">
<input type="text" class="form-control" name="cntc_subj" placeholder="Subject" value="<?=(isset($_POST['ptitle']))?"Queries for $_POST[ptitle]":""?>" required>
<textarea class="form-control" name="cntc_desc" rows="6" placeholder="Your Detail" required></textarea>
<div class="form-group">
<div id="captcha" class="center-captcha"></div>
<div id="gcaptcha" style="transform:scale(0.50);-webkit-transform:scale(0.50);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
<span class="text-danger">*Please complete the form to proceed.</span>
</div>
<!-- <button type="submit" class="btn btn-success btn-block"><i class="fa fa-envelope-o"></i> Submit Form</button> -->
</form>
</div>
You should do this....
//register a event for form submit
$( "form" ).submit(function( e ) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(), //serialize the form data
success : function(data){
$("#contact").html(data);
}
});
});
var verifyCallback = function(e) {
//submit form
$("#form-contact").submit();
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};

Google Form Response not working from the website

I'm using a Google Form's value to integrate with my website where I want to submit the form and store data in google sheet as form responses. I'm using AJAX to redirect to another page instead of google form submit page. But whenever I'm trying to submit it's redirecting to my page accurately but datas are not saved in google sheet. Here are my codes,
<strong>Full Name</strong>
<input type="text" name="Fullname" class="form-control" id="Fullname" />
<strong>Email Address</strong>
<input type="text" name="Email" class="form-control" id="Email" />
<strong>Subject</strong>
<input type="text" name="Subject" class="form-control" id="Subject" />
<strong>Details</strong>
<textarea name="Details" rows="8" cols="0" class="form-control" id="Details"></textarea><br />
<button type="button" id="btnSubmit" class="btn btn-info" onclick="postContactToGoogle()">Submit</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry_805356472": fullname,
"entry_1998295708": email, "entry_785075795":
subject, "entry_934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
How can I save the data in google sheet? Am I missing something in my code? Need this help badly? Thanks.
You can directly copy the form from google view form page like shown in the demo, and then do the following changes in the AJAX call as shown below.
And now once you submit data it is visible in google forms, view responses.
$(function(){
$('input:submit').on('click', function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse",
data:$('form').serialize(),
type: "POST",
dataType: "xml",
crossDomain: true,
success: function(data){
//window.location.replace("youraddress");
//console.log(data);
},
error: function(data){
//console.log(data);
}
});
});
});
<div class="ss-form"><form action="https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse" method="POST" id="ss-form" target="_self" onsubmit=""><ol role="list" class="ss-question-list" style="padding-left: 0">
<div class="ss-form-question errorbox-good" role="listitem">
<div dir="auto" class="ss-item ss-text"><div class="ss-form-entry">
<label class="ss-q-item-label" for="entry_1635584241"><div class="ss-q-title">What's your name
</div>
<div class="ss-q-help ss-secondary-text" dir="auto"></div></label>
<input type="text" name="entry.1635584241" value="" class="ss-q-short" id="entry_1635584241" dir="auto" aria-label="What's your name " title="">
<div class="error-message" id="1979924055_errorMessage"></div>
<div class="required-message">This is a required question</div>
</div></div></div>
<input type="hidden" name="draftResponse" value="[,,"182895015706156721"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fvv" value="0">
<input type="hidden" name="fbzx" value="182895015706156721">
<div class="ss-item ss-navigate"><table id="navigation-table"><tbody><tr><td class="ss-form-entry goog-inline-block" id="navigation-buttons" dir="ltr">
<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action ">
</td>
</tr></tbody></table></div></ol></form></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
If you go to your form on Google and click on 'View Live Form', and then view source on the form, you'll see that the fields you want to upload have aname in the form entry.12345678; the id is in the form entry_12345678. You need to use the name value. Try this:
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry.805356472": fullname,
"entry.1998295708": email,
"entry.785075795": subject,
"entry.934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>

Check if form is completed before activating submit button

I am creating a form where a user has to fill out several fields and then click sign up. However, I want JavaScript to check if the passwords match, and if they don't or a field is left empty to put the signup button into a disabled state with Bootstrap. However, nothing is working. Here is my code:
JSFIDDLE: http://jsfiddle.net/jbe65/
echo '
<h3>Don\'t have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<br><br>
<p id="submit">button class="btn btn-primary btn-block" type="submit">Sign Up/button></p>
</form>
<script>
var empty = "";
var email = $(\'#email\').val()\;
var pass = $(\'#pass\').val()\;
var passver = $(\'#passver\').val()\;
if (empty == email)
{
if (pass != passver)
{
document.getElementById("submit").innerHTML=\'<button class="btn btn-primary btn-block" type="submit" disabled="disabled">Sign Up</button>\';
}
}
</script>
';
I will suggest make the button lookalike disable (by css) and once all the cond pass can make it enable (by css)..
$(document).ready(function () {
$("#formid").on("submit", function (e) {
var empty = "";
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if (empty == email || pass !== passver)
{
alert("please enter valid email and password.");
e.preventDefault();
}
else
{
//u can call this in textbox blur also...
$("#sub").removeClass("disable");
}
});
});
Fiddle Demo
I'm assuming you are using PHP. If so, you can replace the echo statement with a closing PHP bracket ?> to escape the parser. It's generally easier to deal with.
To answer the question at hand, since you are using jQuery, there is no need to change the innerHTML of the p tag, just use the .prop() function, like so:
?>
<h3>Don't have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<p id="submit"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></p>
</form>
<script>
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if ("" == email)
{
if (pass != passver)
{
$('#submit button').prop('disabled', true);
}
}
</script>
<?php
If you're using HTML5 , Put "Required" and then the submit button will not be loaded if there is an empty field Ex :

Categories

Resources