Call a function after a form is submitted using jquery - forms

I'm trying to call a function after any form with the class shown below is submitted. However, this doesn't seem to be working for me (the form submits, but the submit button remains active and the loading image is not shown).
$(document).ready(function() {
$('.uniForm').submit(function() {
$('#loadingImage').show();
$(':submit',this).attr('disabled','disabled');
return true;
});
});
Here's some HTML:
<form class="uniForm" id="formABC">
//...form.... here
</form>
<img src="loadimage.gif" style="display: none;" id="loadingImage">
does anyone see anything inherently wrong with this that would be preventing things from working correctly?
I have a feeling it's just not being called correctly. Can I call it myself via some HTML like this?
<button type="button" class="primaryAction" alt="Submit Form" onclick="$('#formABC').submit();">Submit Form</button>

Following your comment, it seems the binding of the handler function to the submit event might be taking place before the form element has been loaded into the DOM.
Ideally, you should bind event handlers only after the DOM has finished loading.
For example:
$(document).ready(function() {
$('.uniForm').submit(function() {
...
});
});

Put an id on the submit input/button and try this:
$('#mySubmitButton').click(function(e) {
e.preventDefault();
e.stopPropagation();
$(this).attr('disabled','disabled');
$('#loadingImage').show(function() {
$(this.form).submit();
});
});

There is a jQuery plugin named jQuery Form Plugin which helps to submit your form from ajax without refresh and then you can do the rest of actions on its success (which occurs exactly after successful form submission):
jQuery(document).ready(function () {
jQuery('#my_submit_button').click(function (e) {
jQuery(this.form).ajaxSubmit({
target: false,
success: function ()
{
your_other_stuff();
},
});
});
});
function your_other_stuff(){
// rest of things
}

Try something else:
$('.uniForm input[type=submit]').click(function(){
$('.uniForm').submit();
//doStuffafterSubmit
});

Related

Hide mailchimp embed form only when submitting successfully

I have an embed Mailchimp form on my site.
I managed to make it hide when you click the subscribe button, with this:
<script>
$(function(){
$(".mc-btn").on("click", function(){
if ( $('#mce-success-response:visible') ) {
console.log('Successfully signed up');
$('#mc-embedded-subscribe-form').hide();
else {
console.log('Not successfull')
}
}
});
});
</script>
But it does it even if there is error messages.
I have tried:
if($('#mce-success-response').css('display') == 'block')
It does not work at all.
When the success message is visible it looks like this:
<div class="response" id="mce-success-response" style="display: block;">*Success message*</div>
How do i check correctly if the success message is visible?

mixpanel track form submission with validation

I have a form which I want to use mixpanel to track some properties when I submit. How can I stop the form submit through mixpanel if the validation return false ?
Here's my code in general.
My simple form
<form id="form" action="..." method="post" role="form">
// my elements here
<input type="submit" value="Submit" />
</form>
My script
<script>
function(){
mixpanel.track_forms("form", "MyEventName", getProperties());
$("form").submit(SubmitForm);
function getProperties(){
// get properties here
}
function SubmitForm() {
if (SomethingNotRight()) { return false; }
return true;
}
}
My problem:
I expect that in my SubmitForm function, after validation by SomethingNotRight function, it will stop the submit. However, even when SubmitForm returns false, the form keep submitting to the server, which I found out is because of the mixpanel.track_form.
The reason I use mixpanel.track_form is to avoid the race condition between form submit and mixpanel submit as debugging mixpanel track form
I can definitely understand the issue here, and the reason is that track_forms is just designed for the default use case of a form submitting right away. If you have a process in between (in this case a validation), you should basically do your own implementation. The idea of track_forms is to identify the form being submitted, log the event, wait for a while so that the event can be saved, and then proceed. In that sense, you can do:
(function(){})(
var theForm = $("#form"),
readyToProceed = false;
//listen for the submition
theForm.submit(function(e){
if(!readyToProceed){
e.preventDefault();
processSubmit();
}
});
function processSubmit(){
//validation process
if (SomethingNotRight()) { return false; }
//we are all good, lets proceed
mixpanel.track("Form submitted");
readyToProceed = true;
window.setTimeout(function(){ theForm.submit() }, 300);
}
);

DOM elements not accessible after onsen pageinit in ons.ready

I am using the Onsen framework with jQuery and jQuery mobile, it appears that there is no way to catch the event that fires once the new page is loaded.
My current code, which executes in the index.html file (the master page)
<script src="scripts/jQuery.js"></script>
<script src="scripts/jquery.mobile.custom.min.js"></script>
<script src="scripts/app.js"></script>
<script>
ons.bootstrap();
ons.ready(function() {
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
});
in app.js is the following code
function initRecentPage() {
$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
ons.compile(content);
}
and the HTML:
<ons-page id="recentPage">
<ons-toolbar id="myToolbar">
<div id="toolBarTitle" class="center">Recent Checks</div>
<div class="right">
<ons-toolbar-button ng-click="mySlidingMenu.toggleMenu()">
<ons-icon icon="bars"></ons-icon>
</ons-toolbar-button>
</div>
</ons-toolbar>
<ons-scroller>
<h3 class="headingTitle"> Checks</h3>
<div id="Free" class="tabArea">
<ons-list id="yourReports">
</ons-list>
<ons-button id="clearFreeRecentButton">
<span id="clearRecentText" class="bold">Clear Recent Checks</span>
</ons-button>
</div>
</ons-scroller>
</ons-page>
in this instance the variable 'content' is always null. I've debuged significantly, and the element I am trying to get is not present when this event fires. It is loaded later.
So, the question is, how do I ensure that all of the content is present before using a selector. It feels like this is an onsen specific issue.
In the end I could only find one reliable way of making this work.
Essentially I had to wait, using setTimeout 300 milliseconds for the DOM elements to be ready. It feels like a hack, but honestly there is no other reliable way of making this behave. The app is in the app store and works well, so even though it seems like a hack, it works:
$(document).on('pageinit', '#homePage', function() {
initHomePage();
});
function initHomePage() {
setTimeout(function() {
setUpHomePage();
}, 300);
}
Move your $(document.body).on('pageinit', '#recentPage', function() { outside of ons.ready block.
JS
ons.bootstrap();
ons.ready(function() {
console.log("ready");
});
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
function initRecentPage() {
//$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
alert(content)
ons.compile(content);
}
I commented out a line because I do not have access to that "recentShowReport"
You can see how it works here: 'http://codepen.io/vnguyen972/pen/xCqDe'
The alert will show that 'content' is not NULL.
Hope this helps.

jQuery Mobile, reload Dom after submit

I try to develop a theme for WordPress with jQuery Mobile.
But I have a problem with comments. Comments are generated by WordPress as http://www.foo.bar/2012/03/post/#comment-62
Problem is the hastag (#) in Url, jQuery Mobie dislikes, I believe. :)
So far, I use following syntax, and my scripts work well...
jQuery('#page').live('pageinit', function() {
jQuery.mobile.ajaxEnabled = false;
});
I tried to apply data-ajax = "false" to my form, without result. Finally, I tried...
jQuery('#page').live('pageinit', function() {
jQuery.mobile.ajaxEnabled = false;
$('#commentform').bind('submit', function() {
jQuery.mobile.ajaxEnabled = true;
});
});
When my page reloads, my scripts are broken!
Any idea or advice would be greatly appreciate. :) I'm a beginner.
Thanks for your help.
Regards,
Vincent
You can specify JQM configuration in the mobileinit event. But this will disable ajax throughout.
$('document').bind('mobileinit', function () {
console.log("mobile init");
$.mobile.ajaxEnabled = false;
}).trigger('mobileinit');
//...
$('document').ready(function () {
// ...
});
Or you can add data-ajax="false" to the form tag without disabling ajax throughout.
<form data-ajax="false">
</form>

Problem posted data with jQuery submit()

I have the script below. I am trying to POST the data and insert it into a database, the jQuery executes just fine, but does not post anything, the action is working properly because when i post the data without the script, the data posts fine and is inserted into the database fine without any errors, so it seems as if the jquery function is posting nothing. can someone please help?
$('#form').live('submit',function(){
$('#form').fadeOut('slow');
$('#div').append("<h2>submittes</h2>");
return false;
});
<form id="form" method="post" action="execute.php" name="form">
<textarea id="text" name="update"></textarea>
<br>
<input type="submit" value="update" id="update-submit">
</form>
EDIT:
$('#form').live('submit',function(){
var updateTextArea = $('#textarea').val();
$.ajax({
type: "POST",
url: "execute.php",
data: updateTextArea,
success: function() {
$('#form').fadeOut('slow');
$('#div').append("<h2>updated</h2>");
}
});
return false;
});
this is what i have for the ajax, but i am still not having any success.
You don't have any AJAX calls in your javascript. You're just fading out the form, appending an h2, and preventing the default action from occurring (which would be to submit the form normally).
Here's a basic example of how to create a POST ajax request:
$('#form').submit(function(){
$.post($(this).attr('action'), { update: $(this).find('#text).val() }, function(){
// success
});
});
Checkout the jQuery API/Docs for more info on this. There are also dozens of tutorials lurking around the net on how to do this.
Well, by returning false from the event handler function, you trigger two things:
prevent the default action (.preventDefault())
stop the event propagation (.stopPropagation())
This prevents that the submit ever happens.
You need to transfer the data on your own within the submit event handler. For instance, create an ajax request which serializes the form data and sends it to your server.
Could look like:
$('#form').live('submit',function(){
$('#form').fadeOut('slow');
$('#div').append("<h2>submittes</h2>");
$.post('execute.php', $(this).serialize(), function(data) {
// do something after success
});
return false;
});