Executing a form after animation is done JQuery - php

I am trying to submit the form only after my animation is done and completed
Code ------> http://pastie.org/5109573
<form action='loginn.php' method='post'>
<fieldset>
<legend>Register</legend>
<label for='username'>Username*:</label>
<input type='text' name='username' id='username' maxlength="50"
/>
<label for='password'>Password*:</label>
<input type='password' name='password' id='password'
maxlength="50" /> <a><input class ="animated" type='submit' name='Submit' value='Submit' /></a>
</fieldset>
</form>
<span></span>
<script src="jquery.js"></script>
<script>
$("form").submit(function () {
event.preventDefault();
if ($("input:first").val() == "correct") {
$("span").text("OKAY :D").show().fadeOut(1000);
$("a").addClass('animated hinge');
$("span").promise().done(function () {
return true;
});
} else {
$("span").text("Not valid!").show().fadeOut(1000);
return false;
}
});
</script>
</body>
</html>
The form gets submitted before the animation is complete !

You'll need to use the animations callback function to submit the form when the animation completes, like so:
$("input[name='Submit']").on('click', function(e) {
e.preventDefault();
var form = $(this);
if ($("input:first").val() == "correct") {
$("span").text("OKAY :D").show().fadeOut(1000, function() {
form.submit();
});
$("a").addClass('animated hinge');
} else {
$("span").text("Not valid!").show().fadeOut(1000);
}
});​

The problem is likely here:
$("form").submit(function() {
event.preventDefault();
You're not declaring event. Try this:
$("form").submit(function(event) {
Edit:
Also, the function you're passing to the done() method doesn't do anything. Returning true from that function won't affect the event; in fact, the event is already handled and gone by the time that function runs.
If you're trying to submit the form with your done callback, you need to do it explicitly. To avoid an infinite loop when it submits again, try specifying a namespace:
$("form").submit(function(event) {
var that = this;
if (event.namespace != 'verified') {
event.preventDefault();
if ($("input:first").val() == "correct") {
$("span").promise().done(function () {
$(that).trigger('submit.verified');
});
} else {
$("span").text("Not valid!").show().fadeOut(1000);
return false;
}
}
});​

Related

Jquery for submiting without refresh (no validation required)

I have a form for Tags that is working OK, with some server validation, I would like to add a Jquery to submit the content without refreshing:
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input type="submit" value="Add" name="add" />
</div>
</form>
Any advice will be highly appreciated.
Check out the jQuery Form Plugin. Using it, you can submit a form without reloading the page like so:
<form id="aForm" action="target.php" method="post>
...
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#aForm").ajaxForm();
});
</script>
The ajaxForm() function also supports all options (such as a callback function) that can be passed to the standard jQuery $.ajax function.
$(document).ready(function() {
$(form).submit( function() { // could use $(#submit).on('click', function(){ as well
$.ajax({
url: 'yourposturl',
data: $(form).serialize(),
Success: function() {
alert('ok');
}
}); //end ajax
return false;
}); //end submit()
});
Should take all form vars , serialize them so the server can receive, the return false is so page doesnt refresh on submit (stops propagation and default)
Add the JQuery javascript library
Turn the submit into a button
<button id="submitbutton" >Add</button>
Add ids to your inputs
<input type="text" id="tag" name="tag" />
And add the jquery to the click for the button ...
<script type="text/javascript">
$(document).ready(function() {
$("#submitbutton").button().click(function(){
$.post("tags.php",{id: $("#id").val(), tag: $("#tag").val()});
});
});
</script>
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input class="button" type="button" value="Add" name="add" />
</div>
</form>
$(function(){
$('.button').click(function(){
var data = $('form').serializeToObject();
$.post('tags.php', data);
});
});
// jQuery Extension to serialize a selector's elements to an object
$.fn.serializeToObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

jQuery $.submit and files not working in IE and FF

<?php
if (!empty($_FILES)){
echo "<pre>";
echo $_FILES['file']['type'];
echo "</pre>";
return;
}
?>
<script type="text/javascript">
function autoUpLoad(){
$("#txtHint").html("<center><img src='include/images/loader.gif' />Reading selected file...</center>");
$(document).ready(function(){
$("#file").change(function(){
$("#myForm").submit(function(data){
$("#txtHint").html(data);
});
});
});
}
</script>
<form id="myForm" method="post" enctype="multipart/form-data">
<input type="file" name="file" id = "file" onchange='autoUpLoad()'/>
<input type="submit" value="Send" />
</form>
<div id="txtHint">
test
</div>
The above code is not working and I am not sure what is wrong here? It works only if I remove these lines:
function(data){
$("#txtHint").html(data);
}
It just doesn't allow me to return data to txtHint. Can anyone explain to me how to make it work?
You are binding a submit event, not fire it.
.submit() method with a callback as parameter is used to bind submit event, without parameter to fire the submit event.
You should do something like below:
$(document).ready(function () {
$("#myForm").submit(function (data) {
$("#txtHint").html(data);
});
$("#file").change(function () {
$("#myForm").submit();
});
});

jquery cant get value of text box

i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.

jQuery / php - Multply forms on page, submit only one

I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.

Form posts data twice

I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}

Categories