I've been trying to use stripe to accept payment and I've been trying to make a rough prototype for it from a guide I found but I can't seem to get it working. The new input named "stripeToken" never inserts after the submit. This causes my PHP script to never execute. I'm trying to understand why it never inserts. Here's the scripts:
Javascript: (In the head of page)
<script src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('mykeyishere');
</script>
<script>
// Event Listeners
$('#payment-form').on('submit', generateToken);
var generateToken = function (e) {
var form = $(this);
// No pressing the buy now button more than once
form.find('button').prop('disabled', true);
// Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
// Prevent the form from submitting
e.preventDefault();
};
</script>
HTML/Javascript: (Tried JS both in the head and in the form)
<form action="index.php" method="POST" id="payment-form">
<script>
var stripeResponseHandler = function (status, response) {
var form = $('#payment-form');
// Any validation errors?
if (response.error) {
// Show the user what they did wrong
form.find('.payment-errors').text(response.error.message);
// Make the submit clickable again
form.find('button').prop('disabled', false);
} else {
// Otherwise, we're good to go! Submit the form.
// Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
// Call the native submit method on the form
// to keep the submission from being canceled
form.get(0).submit();
}
};</script>
<span class="payment-errors"></span>
<div class="row">
<label>
<span>Card Number</span>
<input type="text" data-stripe="number">
</label>
</div>
<div class="row">
<label>
<span>CVC</span>
<input type="text" data-stripe="cvc">
</label>
</div>
<div class="row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" data-stripe="exp-month">
</label>
<input type="text" data-stripe="exp-year">
</div>
<button type="submit">Submit</button>
</form>
You should remove that script tag from inside the form and put it next to the other script tag.
also try wrapping your event binding in a document.ready
$(document).ready(function(){
$('#payment-form').on('submit', generateToken);
var stripeResponseHandler = function (status, response) {
var form = $('#payment-form');
// Any validation errors?
if (response.error) {
// Show the user what they did wrong
form.find('.payment-errors').text(response.error.message);
// Make the submit clickable again
form.find('button').prop('disabled', false);
} else {
// Otherwise, we're good to go! Submit the form.
// Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
// Call the native submit method on the form
// to keep the submission from being canceled
form.get(0).submit();
}
};
var generateToken = function (e) {
var form = $(this);
// No pressing the buy now button more than once
form.find('button').prop('disabled', true);
// Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
// Prevent the form from submitting
e.preventDefault();
};
});
From what I can guess ( and its not a good guess), is that the #payment-form does not get bound correctly because the script is getting ran before the dom is ready?
Also another thing caught my eye. You have e.preventDefault() which stops the form from being submitted, but then you have a responsehandler. does that response handler get called? Is there some request that goes out to stripe and comes back?
Check in your network window and see if that is happening. The form only gets submitted in the form.get(0).submit(); part of the response handler, so after stripe completes.
Related
There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
You cannot attach events before the elements you attach them to has loaded
It is recommended to use eventListeners - here one when the page loads and another when the form is submitted
This works since IE9:
Plain/Vanilla JS
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
Not recommended but will work
If you do not need more than one event handler, you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm() method returns false.
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests.
These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
Use #Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
After changing my button type to submit it's not submitting the form. Somehow, the AJAX request is not working after that. If I change it to type="button" then it's working, but I want this because required validation is not working while giving type="button". It only works when I'm giving button type submit but then the form is not submitting.
<form>
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
$("#passwordButton").on('submit', function(e) {
e.preventDefault();
const email = $("#passwordReset").val();
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
I want my form to be submitted while checking the required condition also.
Quoting from MDN:
Note that the submit event fires on the element itself, and not on any or inside it. (Forms are submitted, not buttons.)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Attach the listener to the click even of the button, or to the submit event of the form.
HTMLFormElement: submit event
Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)
Try click event instead:
$("#passwordButton").on('click', function(e) {
Update: I think simply submit event on the form is enough here as the event will fire on clicking any input type=submit:
$('#myForm').on('submit', function(){
alert('Your form is submitting');
/*
Your code here
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
I think you should just create a normal like <button onclick="Submit()">save</button>
and write Code like that:
Submit(e){
e.preventDefault();
const email = $("#passwordReset").val();
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
}
Add Id or class attribute to your form.
<form id="formYouWantToSubmit">
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
Then,
$("#formYouWantToSubmit").on('submit', function(e) {
const email = $("#passwordReset").val();
// This will validate if email having any value (from string point of view)
if (!email) {
e.preventDefault();// To restrict form submission
//### Do anything here when validation fails
return false;
}
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
Things to remember:
button type submit will ultimately submits the form to current page (due to action attribute is missing)
When we user Ajax to do something we ultimately seek a 'page-load-less' activity. In your case you are doing both submitting the form using submit button and making Ajax request, which will hard to get executed and if any chance it gets executed you won't be able witness any 'success' or 'error' activities because until then page already been reloaded.
I want to insert an email address into my db with an ajax call.
Here comes the problem. Instead of working into the background, it refreshes the page.
alert("yea"); in the success function is not being reached.
What could be the problem?
$(document).ready(function() {
$("#header-subscribe").click(function(){
var str = $("#email").val();
if( validateEmail(str)) {
$.ajax({
url: 'php/signupForm.php',
type: 'GET',
data: 'email='+str,
success: function(data) {
//called when successful
alert("yea");
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
The form:
<form id="hero-subscribe" class="the-subscribe-form" >
<div class="input-group">
<input type="email" class="form-control" placeholder="Enter Your Email" id="email">
<span class="input-group-btn">
<button class="btn btn-subscribe" id="header-subscribe" type="submit">subscribe</button>
</span>
</div>
</form>
The Ajax call has nothing to do with the refresh. You have a submit button and the purpose of the submit button is to submit the form.
The simplest solution would be to not use a submit button:
type="button"
However, binding the event handler to the click event of the button is not good practice. So instead of that and changing the type, bind the handler to the submit event and prevent the default action (which is submitting the form):
$("#hero-subscribe").submit(function(event) {
event.preventDefault();
// ...
});
You need to prevent the default action of the click...
$("#header-subscribe").click(function(event){
event.preventDefault();
You should bind the submit event of form and use event.preventDefault() to prevent the default action of event.
$("#hero-subscribe").submit(function(event) {
event.preventDefault();
//Your code
});
event.preventDefault() the form action, otherwise it submits like a normal form.
$("#header-subscribe").click(function(event){
event.preventDefault(); //stop the default submit action
I know how to validate a form using Semantic UI, and can even read in console the message "Form has no validation errors, submitting." However, where is this submitting to? I want to actually submit the form, but the way Semantic UI is laid out I don't seem to be able to specify where to submit to or anything.
I read this tutorial, but that uses Angular for submission and not just Semantic UI.
Am I missing something really simple here?
You can use jQuery's ajax:
//Get value from an input field
function getFieldValue(fieldId) {
// 'get field' is part of Semantics form behavior API
return $('.ui.form').form('get field', fieldId).val();
}
function submitForm() {
var formData = {
field1: getFieldValue('someId')
};
$.ajax({ type: 'POST', url: '/api/someRestEndpoint', data: formData, success: onFormSubmitted });
}
// Handle post response
function onFormSubmitted(response) {
// Do something with response ...
}
EDIT: also, you can use the onSuccess method of the form to run the submitForm function, ie when you initialize the form:
$('.ui.form').form(validationRules, { onSuccess: submitForm });
onSuccess will only be called when the 'Submit' button is clicked and the form is valid based on the rules you specify.
EDIT: If you want the regular HTML form behavior, you will need to add the semantic css classes to the form tag.
<form class="ui form" method="POST" action="/signup">...</form>
And then you set up the validation rules using jQuery. This will give you the default HTML form behavior, ie when you hit the submit button, it will make a POST request to /signup in the case above. If any of your rules trigger, the submit is prevented until there is no validation errors.
use the original submit button but add semantic button style:
<input type="submit" value="Submit" class="ui button" />
<input type="submit" value="Submit" class="ui teal button big"/>
Semantic UI has it's own API to submit form. for example:
$('.ui.form .submit.button')
.api({
url: 'server.php',
method : 'POST',
serializeForm: true,
beforeSend: function(settings) {
},
onSuccess: function(data) {
}
});
The easiest way is to retrofit a standard HTML form use the code below.
Start with a basic working standard HTML form with a submit button and this will take your values and post them to your form destination, returning the output below your form submit button.
Its a good time to double check you are successfully linking to jquery, semantic javascript and semantic css at this point.
Add class="ui form" to your form tag .
Add the javascript below.
.
$(document).ready(function() {
// validation
$('.ui.form').form({
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter an email'
}
]
}
},
{
inline: true,
on: 'blur',
transition: 'fade down',
onSuccess: validationpassed
});
// called if correct data added to form
function validationpassed() {
// Multiple instances may have been bound to the form, only submit one.
// This is a workaround and not ideal.
// Improvements welcomed.
if (window.lock != "locked") {
var myform = $('.ui.form');
$.ajax({
type: myform.attr('method'),
url: myform.attr('action'),
data: myform.serialize(),
success: function (data) {
//if successful at posting the form via ajax.
myformposted(data);
window.lock = "";
}
});
}
window.lock = "locked";
}
// stop the form from submitting normally
$('.ui.form').submit(function(e){
//e.preventDefault(); usually use this, but below works best here.
return false;
});
function myformposted(data) {
// clear your form and do whatever you want here
$('.ui.form').find("input[type=text], textarea").val("");
//$('.ui.submit.button').after("<div>Message sent. Thank you.</div>");
$('.ui.submit.button').after(data);
}
});
Basic form:
<form action="process.php" method="post" class="ui form">
<div class="field">
<label>title</label>
<input name="email" type="text">
</div>
<input type="submit" class="ui button"/>
</form>
If you want the error message to show in a box rather than within the form itself include this in your form, and remove the words "inline: true," and Semantic UI does the rest:
<div class="ui info message"></div>
NOTE: Using form tags with Semantic UI isn't strictly necessary as you only really need a div with the classes "ui form", however this retrofit code does require a form tag.
What if you don't wana use ajax?!
Use this one:
$( "#reg_btn" ).click(function(event){
event.preventDefault();
$('#register_form').submit();
});
in this case u can use <button> tag... there is no need to use classic tag instead
Semantic UI is based on jQuery and CSS so if you want to submit your form data you have some way to do that:
Send your form data with AJAX
Use some jqQuery plugins like this
Trick!
Put a submit button and set its display to none. When a user clicks on the div button throw that event to the submit button, in this way:
$("div_button_selector").on("click", function(){
$("input[type='submit']").trigger('click');
});
See post Adding errors to form validation doesn't work? for form and error validation. Since Semantic UI is a client side tool for user interface, this is the php for "self submitting / same code page" contact email. Since the purpose of Semantic UI is not logic processing, what language and or method do you want to use for form submission? JS/jquery client side or serverside php, rails, etc.? Keep in mind Semantic UI is dependent on jquery.
<?php
if (isset($_POST["email"]))
{
if ($_POST["email"] != "")
{
$from = htmlentities($_POST["email"]);
$subject = htmlentities($_POST["subject"]);
$message = htmlentities($_POST["message"]);
$message = wordwrap($message, 70);
mail("valid-server-email-username#valid-server-address", $subject, $message, "From: $from\n");
$_POST["email"] = "";
$_POST["subject"] = "";
$_POST["message"] = "";
unset($GLOBALS['email']);
header("location: /");
}
}
If you have a form like this
<div class="ui form segment">
<p>Tell Us About Yourself</p>
<div class="field">
<label>Name</label>
<input placeholder="First Name" name="name" type="text">
</div>
<div class="field">
<label>Username</label>
<input placeholder="Username" name="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="ui blue submit button">Submit</div>
</div>
you can use the foolowing script to send the form
$('.ui.blue.submit.button').on('click', function() {
submitForm();
});
function submitForm() {
var formData = $('.ui.form.segment input').serializeArray(); //or .serialize();
$.ajax({
type: 'POST',
url: '/handler',
data: formData
});
}
There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
You cannot attach events before the elements you attach them to has loaded
It is recommended to use eventListeners - here one when the page loads and another when the form is submitted
This works since IE9:
Plain/Vanilla JS
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
Not recommended but will work
If you do not need more than one event handler, you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm() method returns false.
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests.
These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
Use #Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});