I'm working on a login/registration for a simple web app. I'm using Foundation to do so. The index page shows a login screen and a register button, if the user clicks this a Reveal Modal appears which includes the register form. This form uses abide to do the data validation (email address, matching passswords etc.). I want the 'register' submit button to be disabled if there are any validation errors and then not disabled when everything is good.
I have used the code on the Foundation Docs where it says:
$('#myForm')
.on('invalid.fndtn.abide', function () {
var invalid_fields = $(this).find('[data-invalid]');
console.log(invalid_fields);
})
.on('valid.fndtn.abide', function () {
console.log('valid!');
});
For some reason (that I can't find after much searching) these events aren't firing. My form has the correct ID, my js file is loading correctly (I put console.log messages either side of that jquery code) and I've tried calling:
$(document).foundation('abide','events');
as suggested here. But I'm still not getting any events.
Any ideas? Could it be because I've got it in a modal or something?
Thank you for your time.
EDIT: I found this page here which says to add:
$('#your_form_id').foundation({bindings:'events'});
instead of:
$(document).foundation('abide','events');
But that doesn't seem to change anything either.
Try using $.getScript after loading the form to run the javascript.
eg:
$('#myModal').foundation('reveal', 'open', {
url: 'form.html',
close_on_background_click:true,
success: function(data) {
$.getScript( "form.js", function() {});
}
});
I had the same problem with fancybox and ajax check before submit.
This is my solution that works for sure
<form id="my_form" action="...." method="POST" class="popup" data-abide="ajax">
<input type="text" name="check_this_field_with_ajax" id="check_this_field_with_ajax">
....
</form>
<script type="text/javascript" src="..../js/foundation.min.js"></script>
<script type="text/javascript" src="..../js/foundation/foundation.abide.js"></script>
<script type="text/javascript">
$('#my_form')
.on('invalid.fndtn.abide', function() {
console.log('NOT Submitted');
})
.on('valid.fndtn.abide', function() {
console.log('VALID');
})
.on('submit', function(e) {
var ajaxRequest = $.ajax({
type: 'GET',
url: "....",
data: {xxx: yyy},
cache: false,
dataType: 'json',
});
....
ajaxRequest.done(function() {
if (ok) {
$('#check_this_field_with_ajax').parent().removeClass('error');
$('#my_form').attr({'submit_this_form': 'yes'});
$(document).foundation('abide', 'reflow');
$('#my_form').trigger('submit.fndtn.abide');
}
});
}
</script>
in foundation.abide.js search line "validate : function (els, e, is_ajax) {" and add:
if (
is_ajax &&
form.attr('submit_this_form') === 'yes'
) {
return true;
}
before
if (is_ajax) {
return false;
}
Related
I'm submitting my Stripe Checkout form via AJAX (catching the form submit event) because I have a complex multi-pane HTML form and want to display payment errors from Stripe without having to reload the page and regenerate the form or making the user re-enter a load of info.
This all works fine, except once the Stripe Checkout button is used once it's disabled. After I display the error message on the booking form page, I need the user to be able to click the Stripe button again and try different payment info.
How do I reactivate the Stripe button? Do I need to remove the whole Stripe button script from the DOM (I'm using jQuery) and re-insert it (or similar code) fresh?
My standard Checkout button code:
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="my_stripe_key"
data-image="mylogo.png"
data-name="My Booking Form"
data-zip-code="true"
data-locale="auto"
data-email=""
data-description="Payment for this booking"
data-currency="gbp"
data-amount=""
data-label="Pay and book!">
</script>
and if relevant, my AJAX form submit code:
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val()
},
type: 'POST',
url: 'book',
dataType: 'json',
data: formdata,
success: function(data) {
if (data.response == 'ok') // Payment went through OK
{
// Redirect to booking confirmation page:
window.location.replace(data.url);
} else // Payment failed, alert user to try again
{
$('#erroralert').text('Sorry, payment failed, please try again').removeClass('nodisplay');
}
},
error: function(data) // Server error
{
console.log('Error:', data.responseText);
}
});
// Prevent form submit.
return false;
}
You have an attribute disabled="true" which is set to the submit button element after the form is submitted. You just need to remove this attribute : $('button[type="submit"]').get(0).removeAttr("disabled");.
Example that works :
http://jsfiddle.net/5xq8Lhda
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="booking" action="your-server-side-code" method="POST">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_TYooMQauvdEDq54NiTphI7jx" data-amount="999" data-name="Stripe.com" data-description="Widget" data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto" data-zip-code="true">
</script>
</form>
<script>
$('#booking').get(0).submit = function() {
$('button[type="submit"]').get(0).removeAttr("disabled");
return false;
}
</script>
To use your example, you should do something like that :
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val()
},
type: 'POST',
url: 'book',
dataType: 'json',
data: formdata,
success: function(data) {
if (data.response == 'ok') // Payment went through OK
{
// Redirect to booking confirmation page:
window.location.replace(data.url);
} else // Payment failed, alert user to try again
{
$('#erroralert').text('Sorry, payment failed, please try again').removeClass('nodisplay');
$('button[type="submit"]').get(0).removeAttr("disabled");
}
},
error: function(data) // Server error
{
console.log('Error:', data.responseText);
}
});
// Prevent form submit.
return false;
}
If you intend to submit your form by AJAX, or just generally want more control over the checkout experience, I'd recommend using the Custom Checkout integration here.
Simple Checkout was designed around a very straight-forward use case: fill out the form, complete a simple form submit. You can do things like attempt to grab the submit button and remove the disabled attribute, though Stripe could always change things up, it may not act as you intend.
The Custom integration provides a perfect place for your ajax submit or additional js code, in the token callback,
token: function(token) {
// your form submission or next steps here
}
My users will see a google repcatcha2 (nocaptcha) in a web page. When they solve the captcha (put the tick in the box) the form should be automatically submit.
Is there any way to do that?
Sure you can do it.
In this post I've explained how to insert reCaptcha into a site and to code javascript to verify user and site.
Add a name to your form with reCaptcha: <form method="post" name="myform">
Add document.myform.submit(); code for submitting of the form upon the site verification success event:
<script type='text/javascript'>
var onReturnCallback = function(response) {
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response},
success: function( data ) {
var res = data.success.toString();
if (res)
{ document.myform.submit(); }
} // end success
}); // end $.ajax
}; // end onReturnCallback
</script>
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});
I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.