Radio button value with Ajax/PHP - php

I have a problem with an apparently simple form for a mailing list subscription.
The HTML5 form contains 3 fields:
text input for e-mail address: <input type="email" name="email"
radio button control with 2 choices:
<input type="radio" value="subscribe" name="radio"
<input type="radio" value="unsubscribe" name="radio"
text input for a CAPTCHA check: <input type="text" name="captchavalue"
<form id="contact" name="contact" method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="check" value="01">
<small>*tutti i campi sono obbligatori</small>
<label for="email" id="emailabel">E-mail:<span class="err topp">INDIRIZZO NON VALIDO</span></label>
<input type="email" name="email" id="email" class="textemail">
<label for="subscr" id="subscrlabel">Scelta:<span class="err topp">devi selezionare una scelta</span></label>
<p><input type="radio" name="radio" id="radio" value="subscribe" checked>Iscrizione</p>
<p><input type="radio" name="radio" id="radio" value="unsubscribe">Cancellazione</p>
<img src="captcha.php" id="captchaimg">
<label for="captcha" id="captchalabel">Copiare il codice di verifica<span class="err capter">CAPTCHA ERRATO</span></label>
<input type="text" name="captchavalue" id="captchavalue" class="textcaptcha">
<section id="subber">
Invia richiesta
</section>
</form>
</div>
We have a list of domains which are allowed to ask for subscription contained in an external file .dat, some line in PHP to dynamically create a regular expression to check the email address (just in case of subscription, otherwise any valid email address is allowed)
<?php
$domains = file("domains.dat");
$domcount = count($domains);
for ($i=0; $i < $domcount; $i++) {
$regex .= "(".trim($domains[$i]).")|";
}
$regex = str_replace(".", "\.", $regex);
$regex = "/^([a-zA-Z\.-_0-9]*#(".substr($regex, 0, strlen($regex)-1).")$)/i";
?>
function checkValidCNRAddress(emailAddress) {
var pattern = new RegExp(<? echo $regex ?>);
return pattern.test(emailAddress);
};
function checkValidEmailAddress(emailAdd) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAdd);
};
var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
// statement below is for DEBUG purposes only -- to show the
// value of the radio button (subscription status) in ALL CASES
document.write(usubscr); //DEBUG
//check that a radio button option is checked (default: "subscribe" is checked )
if(!usubscr) {
$("#subscrlabel").children(".err").fadeIn('slow');
}
else if(usubscr) {
// we have *something* selected in the radio button for subscription
$("#subscrlabel").children(".err").fadeOut('slow');
// next, check for validate email addresses using regular expressions
//check on dynamic regex
if (usubscr == "subscribe") {
if(!checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
}
} //else check at least for a valid email address
else if (usubscr == "unsubscribe"){
if(!checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
}
}
}
Then it checks whether the captcha it's OK or not (it sends data to a PHP page captcha_check) and then submits to sendmail.php (which is in charge to send the subscribe/unsubscribe request to our mailserver)
// captcha check
$.ajax(
{
type: 'POST',
url: 'captcha_check.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "false") {
mailsendstatus = false;
$("#captchalabel").children(".err").fadeIn('slow');
}
else if(data == "true"){
$("#captchalabel").children(".err").fadeOut('slow');
if((checkValidCNRAddress(uemail))||(checkValidEmailAddress(uemail))) {
// in this case it's alright
// TRUE
mailsendstatus = true;
$("#subber").html('<img src="img/load.gif" alt="loading...">');
$.ajax(
{
type: 'POST',
url: 'sendmail.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "yes") {
$("#contactwrapper").slideUp(650, function(){
$(this).before("<p>La tua richiesta è stata inviata, grazie.</p>");
});
}
}
}
); //
} //
} //
} //
} //
);
return mailsendstatus;
}
$(document).ready(function(){
$("#contact").submit(function() { return false; });
$("#submitlink").bind("click", function(e){
var usercaptvalue = $("#captchavalue").val();
var emailvalue = $("#email").val();
var subscrvalue = $("#radio").val();
//sends values to sendmail.php
var postchecks = userSendMailStatus(emailvalue, subscrvalue, usercaptvalue);
});
});
</script>
</body>
Can anybody explain this to me:
- when the script verifies the email address, the value of the radio button given is always "subscribe", in any case, even if I check for unsubscription
- but if I type an email address which domain is contained in domains.dat and check the button for unsubscription, the value passed to sendmail.php is "unsubscribe" (as I can see when I receive the e-mail message)
Hope it's clear enough...thank you in advance for your precious help!

Your problem is that you're NOT actually making any AJAX request to sendmail.php AT ALL unless the email is valid and ONLY when the email is valid.
You see, all your validations in JavaScript to check for valid email addresses, are ONLY then:
fading your errors IN => $("#subscrlabel").children(".err").fadeIn('slow');
or
fading your errors OUT => $("#subscrlabel").children(".err").fadOut('slow');
but, this is occurring on the page only
When you actually submit, it fails the AJAX request if the email is invalid, BUT, it is still submitting the form normally and therefore it resets to the default subscribe input state of "checked"
What you need to do is include your .ajax(...) statement/call inside of your validation, not below it, after you've closed the function:
var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
//verify radio button (it's checked by default in our case)
if(!usubscr) {
$("#subscrlabel").children(".err").fadeIn('slow');
}
else {
$("#subscrlabel").children(".err").fadeOut('slow');
//check on dynamic regex
if (usubscr == "subscribe") {
if(!checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
mailsendstatus = true;
}
} //else check at least for a valid email address
else if (usubscr == "unsubscribe"){
if(!checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
mailsendstatus = true;
}
}
}
if (mailsendstatus = true;) {
...
//make your AJAX request here
...
}
}

Related

Contact form - Passing variables from PHP to jQuery

[I suspect the issue at hand has to do with how the php array gets passed to jQuery, if that isn't the case I apologize for the misleading title]
The contact form below is working -- except when I submit the forms' data, sometimes one field always keeps its red border indicating missing input, even when it actually has data.
To elaborate: I have a working php-only solution but on submit it causes a page-reload which I would like to avoid. After some research, it seems I need php/jQuery/ajax to perform these things asynchronously and to stay on the same site.
Desired behaviour:
So there are three required input fields called name, email and message, if any one is left out, it should receive a red border and no email gets sent.
Actual behaviour:
If for example only name and message are filled out and submitted, the empty email field is colored red.
But if a (valid) email is provided, the second submit action does not remove the red border around the email field.
I know that javascript and friends is a client-side language, and PHP gets processed server-side. Once the form is submitted, the .ajax function takes the serialized form values, uses 'POST' to stuff it into the php script and waits for the server to call us back inside .done()
This is where I'm lost - how is the php array to be used in jQuery?
E.g. no matter what, this line is never reached:
console.log("All fields filled and valid");
index.html:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />
<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>
<style>
.input-error
{
border: 2px solid red;
}
</style>
<script>
$(document).ready(function() // Wait until website (DOM) is completely loaded
{
/* Page top */
$('#pagetop').click(function()
{
console.log(this);
$('body, html').animate({scrollTop: '0px'}, 600);
return false;
});
});
</script>
</head>
<body>
<!-- action is left blank as process.php is called from verify.js -->
<form action="" method="POST" id="contactForm">
<label for="company">Company</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
<br><br>
<label for="name">Name *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
<br><br>
<label for="email">Email *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
<br><br>
<label for="message">Message *</label>
<br>
<textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
<br><br>
<input type="submit" id="submit" name="submit" value="Send">
<br><br>
</form>
</body>
verify.js
$(document).ready(function()
{
// process the form
$('#contactForm').submit(function(event)
{
//$('#name, #email, #message').removeClass('input-error');
// process the form
$.ajax(
{
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : $('#contactForm').serialize(),
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data)
{
// log data to the console so we can see
console.log(data);
if (data.errors.name)
{
console.log("Name missing");
$('#name').addClass('input-error');
}
else
{
$('#name').removeClass('input-error');
}
// handle errors for email
if (data.errors.email)
{
console.log("Email missing or invalid");
$('#email').addClass('input-error');
}
else
{
$('#email').removeClass('input-error');
}
// handle errors for message
if (data.errors.message)
{
console.log("Message missing");
$('#message').addClass('input-error');
}
else
{
$('#message').removeClass('input-error');
}
if(data.input_valid == true)
{
console.log("All fields filled and valid");
alert('success');
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
process.php
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// Sanitize input variables
$company = test_input($_POST['company']);
$name = test_input($_POST['user_name']);
$email = test_input($_POST['user_email']);
$message = test_input($_POST['user_message']);
// Validate the variables
// If any of these variables don't exist, add an error to our $errors array
if (empty($name))
$errors['name'] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
$errors['email'] = 'Valid Email is required.';
if (empty($message))
$errors['message'] = 'Message is required.';
$from = '--- Contact Form ---';
$to = 'some#mail.com';
$subject = 'Message from Contact Form';
$body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
if(mail($to, $subject, $body, $from))
{
$data['message'] = 'Thank you for your message!';
$data['mail_sent'] = true;
}
else
{
$data['message'] = 'Message could not be sent - please try again later.';
$data['mail_sent'] = false;
}
}
// return all our data to an AJAX call
echo json_encode($data);
// Convert special characters to html entities to prevent XSS attacks
// Also remove white-space and backslashes
function test_input($val)
{
$val = trim($val);
$val = stripslashes($val);
$val = htmlspecialchars($val);
return $val;
}
?>
It looks like if all validations pass in your php script, then data['errors'] is never defined. This might cause an error to be thrown (that you can see in the browser console) in the javascript when you write:
if (data.errors.name)
data.errors will evaluate to undefined in javascript, and when you try to access a property of undefined like data.errors.name, it will throw an error and stop the script.
To fix this, you probably just need to define errors in your php script, (though I'm not 100% sure the JSON methods won't leave out an empty array...). Try doing this in your php script:
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
$data['errors'] = $errors; // even though it is empty
// etc
EDIT:
I don't know if it will work with your jquery version but just in case it doesn't, place this code in your header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I used the below code and it worked. Sent the email without having to change the PHP code:
$(document).ready(function() {
$('#contactForm').submit(function(event) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#contactForm').serialize(),
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if(data.input_valid == true) {
console.log("All fields filled and valid");
// If the function is a success remove error classes from all fields
// you can either place the below code above the alert so that it happens
// before you get the success message, or after.
$('#name').removeClass('input-error');
$('#email').removeClass('input-error');
$('#message').removeClass('input-error');
alert('success');
} else {
if (data.errors.name) {
console.log("Name missing");
$('#name').addClass('input-error');
} else {
$('#name').removeClass('input-error');
}
if (data.errors.email) {
console.log("Email missing or invalid");
$('#email').addClass('input-error');
} else {
$('#email').removeClass('input-error');
}
if (data.errors.message) {
console.log("Message missing");
$('#message').addClass('input-error');
} else {
$('#message').removeClass('input-error');
}
}
});
event.preventDefault();
});
});

Checking and submitting form via Ajax in boostrap modal

I have a login form in boostrap's modal window
<form method="post" id="loginForm" action="index.php">
<label for="email">Email:</label>
<input class="form-control" type="text" name="email" value="" id="emailLogin"/><br/>
<label for="password">Password:</label>
<input class="form-control" type="password" name="password" value="" id="passwordLogin"/><br/>
<div id="loginAlert" class="alert alert-danger" role="alert">Email or password incorrect</div> <!-- Hidden by default -->
<button type="submit" name="login" class="btn btn-primary" id="loginButton">Login</button>
<script src="checkLoginForm.js"></script></form>
I would like to check this form (if email and password are correct) before submitting it. If the function, which checks the email and password returns 1, there is something incorrect. Form should not submit in this case and it should just make the alert visible.
If everything is correct, it should submit.
Thing is: I can prevent the form from submitting, if the the email and password are incorrect, but I can't submit it, if they are correct. Here is the code from checkLoginForm.js
$(document).ready(function() {
$("#loginForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'include/ajax.php?action=checkLogin',
data: {
email: $("#emailLogin").val(),
password: $("#passwordLogin").val(),
},
success: function(result) {
console.log(result);
if(result == 0) {
} else {
$("#loginAlert").css({"display": "block"});
}
}
});
});
});
I have no idea what to do, when the result == 0. If I do $("loginForm").submit();, that does not submit the form (else part does work).
Thank you for your replies.
I would advice you to use a simple $.post, it's a shorthand way of using $.ajax for POST requests. Just check if the values provided are correct in your php file, if they are correct process that data and return true or redirect the user to another page else return false.
$(document).ready(function() {
$("#loginButton").on('click', function (e){
e.preventDefault();
var email = $("#emailLogin").val();
var passwd = $("#passwordLogin").val();
$.post('include/ajax.php?action=checkLogin', {email: email, password: passwd}, function (data) {
var res = $.parseJSON(data);
if (res.result == true) {
//you can redirect the or display a message to the user.
//redirect the user to another page
//$("#loginAlert").css({"display": "block"}).html("login successful");
}else {
$("#loginAlert").css({"display": "block"});
}
});
});
});
Then in your php file
if (isset($_GET['action']) && $_GET['action'] == 'checkLogin') {
$passwd = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
//validate inputs here
//get data from db
//then compare values
//if values match return true
//$db_mail and $db_passwd are from the db.
if ($email == $db_mail && $passwd == $db_passwd) {
//if the provided information is correct
//process it here, login the user.
//redirect if necessary.
// or return results to JS
echo json_encode(['result' => true]);
} else {
//if the information is wrong return false to JS
//and alert the user
echo json_encode(['result' => false]);
}
}

Difficulty processing data from jQuery post to pg_query();

Having the following difficulty.
I'm currently creating a form. This form is made in HTML and controlled by jQuery.
The form code is as following;
<div id="form">
<form>
<label>ID :</label>
<input type="text" id="clientid" /><br /><br />
<label>Name :</label>
<input type="text" id="name" /><br /><br />
<label>IP Address :</label>
<input type="text" id="ipaddress"/><br /><br />
<label>Status :</label>
<input type ="text" id ="status" />
<input type="button" id="button" value="Insert" /><br /><br /><br />
<label id="response"></label>
</form>
Now, this form picks up user data, and gets processed by the following jQuery script;
// Start jQuery script
// jQuery for dynamic adding without complete page reloads
//Wait for document readiness
$('document').ready(function() {
// Define submit button and action
$('#button').click(function() {
// Assign variable
if ($('#clientid').val() == "") {
alert("Enter Client ID");
return false;
} else {
var clientid = $('#name').val();
}
// Assign variable
if ($('#name').val() == ""){
alert("Enter Client full name");
return false;
} else {
var name =$('#name').val();
}
// Assign variable
if ($('#ipaddress').val() == "") {
alert("Enter Client owned IP address");
return false;
} else {
var ipaddress = $('#ipaddress').val();
}
// Assign variable
if ($('#status').val() == "") {
alert("Enter client status");
return false;
} else {
var status = $('#status').val();
}
// When variables are known, continue processing and POST'ing
// Posting to seperate PHP file to complete
jQuery.post("processing/addC.php", {
clientid: clientid,
name: name,
ipaddress: ipaddress,
status: status
},
function(data, textStatus) {
if (data == 1) {
$('#response').html("Insert successful!");
$('#response').css('color', 'green');
} else {
$('#response').html("Insertion failure. Please try again or restart.");
$('#response').css('color', 'red');
}
});
});
});
This code obviously passes the variables through a POST to addC.php.
addC.php contains the following code:
<?php
// Get current connection
include 'dbconnect.php';
$clientid = $_POST['clientid'];
$name = $_POST['name'];
$ipaddress = $_POST['ipaddress'];
$status = $_POST['status'];
$query = pg_query_params(
$dbconnection,
'INSERT INTO clients(clientid, name, ipaddress,status) VALUES ($1, $2, $3, $4);',
array($clientid, $name, $ipaddress, $status)
);
if(pg_affected_rows($query)>0){
echo "1";
}else{
echo "2";
}
?>
The desired result of this code is the if-statement returning a 1, so the jQuery can create a nice green message saying the database insertion went correct.
Now, as I validated the pg_query(); syntax to be correct, there must be something wrong in this code itself. What seems to be the problem here?
EDIT:
Following error;
Warning: pg_query_params(): Query failed: ERROR: invalid input syntax for integer: "michael" in /Applications/XAMPP/xamppfiles/htdocs/LoginHQ/processing/addC.php on line 18
invalid input syntax for integer: "michael"
It means that column has type integer, but you try insert string

Required alert on wordpress form

The contact form it´s working, if you fill it all it sends the message. The problem if you don´t fill in the email box, the form doesn´t alert you about it, is there anyway that I can show a word or somekind of alert to the user?
this is my markup:
<div class="form">
<h2>ESCRIBENOS</h2>
<form method="post" action="process.php">
<div class="element">
<label>Nombre (obligatorio):</label><br/>
<input type="text" name="name" class="text" />
</div>
<div class="element">
<label>Email (obligatorio):</label><br/>
<input type="text" name="email" class="text" />
</div>
<div class="element">
<label>Telefono:</label><br/>
<input type="text" name="website" class="text" />
</div>
<div class="element">
<label>Mensaje:</label><br/>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
And this is my script:
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website=' +
website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "../process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
Can someone help me out please?
Try this:
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
return false;
}
});
.... rest of your code
Note: This does not work for textarea but I think you can figure that out yourself!
EDIT:
var valid = false;
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
valid = false;
}else{
valid = true;
}
});
if(valid == false) return;
console.log('All input fields are filled in..');
... rest of your code. You can remove al the if else statements for input fields. For checking the textarea you could give all fields the same class and do:
$('form.classofallelements').each(function(){

SUBMIT FORM with mouse clicking and enter button

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.

Categories