I am Submiting form through MOUSE CLICK and ENTER too.
Ajax Call is checking is there any designation which i already in DATABASE.. If not, user can submit form otherwise SUBMIT button will DISABLE
JQUERY
function check_designation(e){
text = $('#req1').val();
data = "data=" + text;
text_length = text.length
if(text_length == 0)
{
$('#result_span').html('');
}
if(text_length > 3 ){
$.ajax({
url: "designation_ajax.php",
type: "POST",
data: data,
cache: false,
success: function (response) {
if ($.trim(response) == "access") {
$("#result_span").html('<div class="green">' + text + ' is available '+'</div>');
$('#create_desg').removeAttr('disabled');
}
else if ($.trim(response) == "no access") {
$("#result_span").html('<div class="red">' + text + ' is already in use'+'</div>');
$('#create_desg').attr('disabled','disabled');
}
else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
}
else{
$("#result_span").html('');
}
return true;
}
HTML FORM
<form id="formID" class="formular" method="POST" action="" onsubmit="formSubmit()" >
<fieldset>
<legend>Create Desination</legend>
<label> Designation<br clear="all" />
<input autocomplete="off" onkeyup="check_designation(event)" value="" class="validate[required,minSize[4]] text-input float_left" type="text" name="name" id="req1" />
<span id="result_span"></span>
</label>
<br clear="all" />
<input id="create_desg" value="Submit" type="button" />
</fieldset>
</form>
PROBLEM::::
Now what happen DISABLE button is not a solution... if there is already a DESIGNATION in a table.. submit button will disable but By ENTER it will submitted and i dont want to reload the page. and AJAX is not working when i PRESS ENTER
You must return false from your onsubmit handler in order to cancel the default action. But I would probably clean your code a bit and subscribe to the submit event unobtrusively:
<form id="formID" class="formular" method="POST" action="">
<fieldset>
<legend>Create Desination</legend>
<label>
Designation<br clear="all" />
<input autocomplete="off" value="" class="validate[required,minSize[4]] text-input float_left" type="text" name="name" id="req1" />
<span id="result_span"></span>
</label>
<br clear="all" />
<input id="create_desg" value="Submit" type="button" />
</fieldset>
</form>
You will notice that I have intentionally removed the onkeyup event from the input field. Hammering your server with AJAX requests every time some user hits a key while inside this field won't do any good to your server. If you want to implement this I would recommend you waiting for some input to accumulate and throttle before sending the AJAX request.
and then:
$(function() {
$('#formID').submit(function() {
var text = $('#req1').val();
if(text.length == 0) {
$('#result_span').html('');
}
if(text.length > 3) {
$.ajax({
url: 'designation_ajax.php',
type: 'POST',
data: { data: text },
cache: false,
success: function (response) {
if ($.trim(response) == 'access') {
$('#result_span').html('<div class="green">' + text + ' is available '+'</div>');
$('#create_desg').removeAttr('disabled');
}
else if ($.trim(response) == 'no access') {
$("#result_span").html('<div class="red">' + text + ' is already in use'+'</div>');
$('#create_desg').attr('disabled', 'disabled');
} else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
} else {
$('#result_span').html('');
}
// return false to prevent the default action
return false;
});
});
Also I would have the designation_ajax.php script return JSON instead of some access and no access strings that you are parsing and trimming in your success callback.
Related
I am trying to submit the form on my page upon page load if there are certain parameters set in the query string. The form submits using ajax and works fine and the pre-population of the form fields from the query string is fine aswell but no matter what I try to automatically submit the form, I end up in an infinite loop of page loads.
PHP
// top of page
<?php
if (isset($_GET['postcode'])) {
$postcode = trim($_GET['postcode']);
} else {
$postcode = '';
}
if (isset($_GET['phone_num'])) {
$phone_num = trim($_GET['phone_num']);
} else {
$phone_num = '';
}
?>
jQuery
/*
// causing infinite page loads
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
return false;
}
*/
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<button type="submit" class="btn btn-primary" id="check">Check</button>
</form>
Instead of using a click function for the auto form submit I've tried doing the same $('form').submit but I get the same problem. I was expecting the page to function as normal so that if the parameters were set then the ajax call would automatically be made but this is obviously not the case.
You're exiting your code before you bind the submit event. Remove the return false in your if statement, then move the if statement to after the submit binding.
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
//return false;
}
Try something like this:
if($('input[name="phone_num"]').val() && $('input[name="postcode"]').val()) {
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
}).submit();
}
use this line on your code.
$('form').trigger("submit");
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<input type="button" class="btn btn-primary" id="check">Check</button>
</form>
jQuery
$('#check').click(function(e) {
e.preventDefault();
$.get("script.php", $('form').serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
}
When using a submit button, you are performing the default event (submitting the form) as well as processing the handler of the .click() event. To avoid this, use e.preventDefault(); causing only the scripted portion of the event to process.
I'm making a ajax call to a server side function to send an email. It works fine. My issue is before sending the email i need to validate the captcha where the server side code resides in CaptchaValidation.php. If i call "CaptchaValidation.php" on form action it should work fine but here since i'm doing a ajax call i need to use e.preventDefault();. So that form action is not working.
How can i make it work?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divLoading').hide();
$('#appointment').submit(function (e) {
e.preventDefault();
var serviceURL = 'WebService.asmx/SendMail';
var Name = $("#fname").val();
var Email = $("#email").val();
var Telephone = $("#phone").val();
var Comment = $("#comment").val();
if ($("#fname").val().length == 0) {
alert("Please Enter Name");
$("#fname").focus();
return false;
}
if ($("#email").val().length == 0) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf("#") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf(".") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
$('#divLoading').show();
$.ajax({
type: "POST",
url: serviceURL,
data: '{"name":"' + Name + '","address":"' + Email + '","telephone":"' + Telephone + '","comment":"' + Comment + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
// alert("Mail Sent!");
$('#divLoading').hide();
window.location = "contat-submit.php";
}
function errorFunc() {
// alert('error');
}
});
});
</script>
</head>
<body>
<form name="appointment" id="appointment" method="post" action="CaptchaValidation.php">
<div>
</div><div id="leftcolumn4"><div class="h2">Contact Form</div>
<form name="appointment" id="Form1" method="post" action="send_contact.php">
Full Name:
<br />
<label>
<input name="fname" type="text" class="form-input" id="fname" size="30" />
</label>
<br /><br />
Email Address:<br />
<label>
<input name="email" type="text" class="form-input" id="email" size="30" />
</label><br /><br />
Telephone:
<br />
<label>
<input name="phone" type="text" class="form-input" id="phone" size="30" />
</label>
<br /><br />
Your Comment:<br />
<label>
<textarea name="comment" cols="28" rows="4" class="form-input-box" id="comment"></textarea><br />
<br />
</label><input name="submit" type="submit" class="form-input-submit" value="Submit" id="btnMail"/>
</div>
</form>
</body>
</html>
Follow the steps:
Change the Submit button to a simple button so that on click of that button the form will not submit.
On Click of that button call a function which will have call e.preventDefault();
function callSubmit() {
// do ajax call
}
You are doing ajax call in e.preventDefault() function. So in AJAX response, you have to check if the AJAX response is correct then do a form submit using:
$('#appointment').submit()
Now just remove the e.preventDefault(); function from you form.submit function you have written. This will allow to AJAX submit and send email.
i am trying to use fancybox to display login form like bellow
<div style="display:none">
<form id="login_form" method="post" action="">
<p id="login_error">Please, enter data</p>
<p>
<label for="login_name">Login: </label>
<input type="text" id="login_name" name="login_name" size="30" />
</p>
<p>
<label for="login_pass">Password: </label>
<input type="password" id="login_pass" name="login_pass" size="30" />
</p>
<p>
<input type="submit" value="Login" />
</p>
<p>
<em>Leave empty so see resizing</em>
</p>
</form>
</div>
the java script for that is
$("#login_form").bind("submit", function() {
if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
$("#login_error").show();
$.fancybox.resize();
return false;
}
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "login.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
the html is
<a id="tip5" title="Login" href="#login_form"><?php echo "Login" ; ?></a>
when i click on login link, it shows the login popup but when i click on submit button it close the popup and refresh the page.
actually it should check the data and display data on popup not refresh page.
Thanks
There could be more problems:
Fancybox is probably cloning the original HTML to put it into the popup. Therefore You need to use function live instead of bind.
It is possible that Fancybox could alter the form's ID in some way (check that with some DOM Inspector like FireBug for FireFox) and assure that the form's ID within a popup is the one You'd lived the submit event for.
I also prefer to use event.preventDefault() instead of returning false... My JS code would then be:
$("#login_form").live("submit", function(e) {
e.preventDefault();
if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
$("#login_error").show();
$.fancybox.resize();
return false;
}
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "login.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
});
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.
I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info.
http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username.
http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why.
Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this.
Here's the code from the first example:
<form method = "post"
action = "">
Username: <input type="text" name="login_name" value="" />
<br><br>
Password: <input type="password" name="password" value="" />
<br><br>
<input type="submit" value="Login" />
</form>
Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php
<p>
Email address: <input type="text" id="logininfo" value="" />
<br>
Password: <input type="password" id="password" value="" />
<br>
<input type="button" id="loginbutton" value="Login" />
</p>
Here is the jquery used in the second example:
<script type ="text/javascript">
$(function(){
$('#loginbutton').click(function(){
var loginvar = $('#logininfo').val();
var passvar = $('#password').val();
//alert(loginvar + ", " + passvar);
if (loginvar != '' && passvar != '') {
var subdata = {
logindata : loginvar,
passdata : passvar
};
$.ajax({
url: "index_backend.php",
type: 'POST',
data: subdata,
success: function(result) {
//alert(result);
if (result == '1') {
// success
window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php")
} else if (result == '2') {
//$('#logininfo').empty();
$('#logininfo').attr('value', '')
$('#password').attr('value', '')
alert("Login failed. Please try again, or register if you have not already created an account.");
} else {
alert("Something has gone wrong!");
alert (result);
}
} // end success
}); // end ajax
} else {
alert ("Please enter a username and password.");
}
}); /// end click function for button
}); //// end
</script>
Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.