deny submitting form if the username exist on the mysql db - php

i just pluged a JQuery username check which worked fine , the problem is that my form still submitting even the username exist on my Mysq Database, how can i configure it to deny submitting to my server side .php file if it exists ?
here is my Jquery plugin javascript code
$(document).ready(function() {
//the min chars for checkusername
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = '<img src="images/checkusername.gif" /> Checking...';
//when button is clicked
$('#check_checkusername_availability').click(function(){
//run the character number check
if($('#checkusername').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#checkusername_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#checkusername_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check checkusername availability
function check_availability(){
//get the checkusername
var checkusername = $('#checkusername').val();
//use ajax to run the check
$.post("frontend/functions/f_checkuser.php", { checkusername: checkusername },
function(result){
//if the result is 1
if(result == 1){
//show that the checkusername is available
$('#checkusername_availability_result').html('<span class="is_available"><b>' +checkusername + '</b> is Available</span>');
}else{
//show that the checkusername is NOT available
$('#checkusername_availability_result').html('<span class="is_not_available"><b>' +checkusername + '</b> is not Available</span>');
}
});
}
here is my html field
<table border="0" >
<tr>
<td valign="middle"><input class="input_field_12em required userUserName" name="userUserName" id="checkusername"></td>
<td valign="middle"><input type='button' id='check_checkusername_availability' value='Check Availability'></td>
<td><div id='checkusername_availability_result'></div></td>
</tr>
</table>

You can wait for the callback to fire for your AJAX request, then you can either submit the form or not:
$(function () {
$('form').on('submit', function (event, extra) {
if (typeof extra == 'undefined') {
extra = false;
}
//if no extra argument is passed via `.trigger()` then don't submit the form
return extra;
});
$('#check_checkusername_availability').on('click', function () {
$.ajax({
url : 'frontend/functions/f_checkuser.php',
type : 'post',
data : { checkusername : $('#checkusername').val() },
success : function (serverResponse) {
//now check the serverResponse variable to see if the name exists, if not then run this code:
$('form').trigger('submit', true);
},
error : function (jqXHR, textStatus, errorThrown) { /*don't forget to handle possible errors*/ }
});
});
});
Otherwise, you can force the AJAX request to be synchronous by setting async:false, but this will lock-up the browser until the AJAX request resolves, which could be seconds where the user can't do anything. This gives the impression that your script is broken to the user.

You didn't post your html but it seems like clicking on object with id check_checkusername_availability triggers form submit in some way. Is it a submit button? If that's the case just change it to the regular button. And add callback to handle the resonse.

Related

Form submitting with "email already exist" conditon in Php using ajax

I am working with ajax Php, I want to check email availability using ajax(on blur function)
my code is working fine, showing whether email exists or not but my form submitting even " email already exists " message showing
, I just want that form should not submit if I enter existing email, Here is my code, Where I am wrong?
<script type = "text/javascript" >
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function() {
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if (filter.test(email_val)) {
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/Register/email_check", {
email: email_val
}, function(response) {
alert(response);
$('#loading').hide();
//$('#message').html('').html(response).show().delay(4000).fadeOut();
if (response.trim() == '1') {
$('#failuremsg').show().delay(4000).fadeOut();
} else {
$('#successmsg').show().delay(4000).fadeOut();
}
});
return false;
}
});
});
</script>
replace the submit button on the form with
<button id="submit-form">Submit</button>
set a validated=true variable in your main code when all checks have passed
add some jquery
$( "#submit-form" ).click(function() {
if(validated){
$( "#yourForm" ).submit();
}else{
return false;
}
};

Form submission according to ajax condition is not working

I have a form submission page, call a function at the time of form submission.Include an ajax.Form submission occur or not according to the condition in ajax.Ajax msg have two values 1 and 0,one value at a time.My requirement is when msg==1 form not submit and msg==0 submit form.But now in both cases form is not submitting.
My code is given below.Anybody give any solution?
main page
<form action="addCustomer_basic.php" method="post"
name="adFrm" id="myform" >
<input name="name" type="text"
class="txtfld" id="name"
value=">" style="width:250px;"/>
<input name="email" type="text"
class="txtfld" id="email" value="" style="width:250px;"/>
<input name="submit" type="submit" value="Submit" />
</form>
<script language="JavaScript">
$(function() {
$("#myform").submit(function(e) {
var $form = $(this);
var cust_name = $form.find('[name="name"]').val();
e.preventDefault();// prevent submission
var email = $form.find('[name="email"]').val();
$.ajax({
type: "POST",
url: 'ajx_customer_mailid.php',
data:'cust_name='+cust_name + '&email=' + email,
success: function(msg)
{
alert(msg);
if(msg==1)
{
alert("Email Id already excist in database");
return false;
}
else
{
self.submit();
}
}
});
});
});
</script>
ajx_customer_mailid.php
<?php
require_once("codelibrary/inc/variables.php");
require_once("codelibrary/inc/functions.php");
$cust_id=$_POST['cust_name'];
$email=$_POST['email'];
$se="select * from customer where name='$cust_id' and email='$email'";
$se2=mysql_query($se);
if($num>0)
{
echo $status=1;
}
else
{
echo $status=0;
}
?>
I've checeked your code, without ajax, and just set directly the msg to 1 or to 2.
See my code, now you can simulate it:
$("#myform").submit(function(e) {
var $form = $(this);
e.preventDefault();// prevent submission
var msg = 2;
if (msg === 1) {
alert("Email Id already excist in database");
return false;
} else {
$form.submit(); //This causes Too much recursion
}
});
There are some errors in it.
So, self.submit(); is bad:
TypeError: self.submit is not a function
self.submit();
You need to rewrite it to $form.submit();
But in that case, if the form needs to submit, you will get an error in your console:
too much recursion
This is because, if it success, then it fires the submit again. But, because in the previous case it was succes, it will be success again, what is fires the submit again, and so on.
UPDATE:
Let's make it more clear what happens here. When you submit the form, after you call e.preventDefault() what prevents the form to submit. When ajax need to submit the form, it triggers the submit(), but you prevent it to submit, but ajax condition will true again, so you submit again, and prevent, and this is an inifinte loop, what causes the too much recursion.
NOTE:
if($num>0) Where the $num is come from? There are no $num anywhere in your php file. You also do not fetch your row of your sql query.
Use mysqli_* or PDO functions instead mysql_* since they are deprecated.
Avoid sql injection by escaping your variables.
So you need to use like this:
$se = "select * from customer where name='$cust_id' and email='$email'";
$se2 = mysql_query($se);
$num = mysql_num_rows($se2); //NEED THIS!
if ($num > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
But i am suggest to use this:
$se = "SELECT COUNT(*) AS cnt FROM customer WHERE name='".mysql_real_escape_string($cust_id)."' and email='".mysql_real_escape($email)."'";
$se2 = mysql_query($se);
$row = mysql_fetch_assoc($se2); //NEED THIS!
if ($row["cnt"] > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
By the time your ajax call finishes, submit handler already finished so the submit continues, it's async you know, so the function makes the ajax call and continues executing. You can do something like this http://jsfiddle.net/x7r5jtmx/1/ What the code does is it makes the ajax call, then waits until the ajax success updates the value of a variable, when the value is updated, if the value is 1, no need to do anything, as we already stopped the form from submittin. If the value is 0, then trigger a click on the button to re-submit the form. You can't call submit inside the submit handler, but you can trigger click on the button. You obviously need to change the ajax call, just set msg inside your success.
var data = {
json: JSON.stringify({
msg: 0 //change to 1 to not submit the form
}),
delay: 1
}
var msg = null;
var echo = function() {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: data,
cache: false,
success: function(json){
msg = json.msg;
}
});
};
$( "#myform" ).submit(function( event ) {
echo();
var inter = setInterval(function(){
console.log("waiting: " + msg);
if (msg != null){
clearInterval(inter);
}
if (msg == 0){
$( "#myform" ).off(); //unbind submit handler to avoid recursion
$( "#btnn" ).trigger("click"); //submit form
}
}, 200);
return false; //always return false, we'll submit inside the interval
});

returning value from ajax, back to the JS function that it

here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

real time validation of username and email address using ajax post

I set up a simple form and use ajax+jquery to check for valid username (doesn't exist in DB) and email address (valid format and doesn't exist in DB) as follows
<body>
<div>
<h5> Sign Up </h5>
<hr />
<div>
Username:<input type="text" size="32" name="membername" id="username"><div id="usernameStatus"></div><br />
Email:<input type="text" size="32" name="memberemail" id="memberemail"><div id="emailStatus"></div><br/>
Password:<input type="password" size="32" name="memberpwd"><br />
<button id="signup" disabled="true">Sign Up</button>
</div>
<script>
function IsEmailValidAndNew()
{
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);
var success=false;
$("#memberemail").change(function()
{
var email=$("#memberemail").val();
success=patter.test(email);
if(success)
{
$("#usernameStatus").html('<img align="absmiddle" src="loading.gif"/> Checking email...');
$.ajax(
{
type: "POST",
url:"regcheckemail.php",
data:"memberemail="+email,
success: function(msg)
{
$("#emailStatus").ajaxComplete(function(event, request, settings)
{
if(msg=="OK")
{
$("#memberemail").removeClass("object_error");
$("#memberemail").addClass("object_ok");
$(this).html('<img align="absmiddle" src="checkmark.png"/>');
success=true;
}
else
{
$("#memberemail").removeClass('object_ok');
$("#memberemail").addClass("object_error");
$(this).html(msg);
success=false;
}
}
);
}
}
);
}
else
{
$("#emailStatus").html("Provided email address is ill-formed");
$("#memberemail").removeClass('object_ok'); // if necessary
$("#memberemail").addClass("object_error");
success=false;
}
}
);
return success;
}
function IsUserAlreadyExist()
{
var success=false;
$("#username").change(function()
{
var usr=$("#username").val();
if(usr.length>=7)
{
$("#usernameStatus").html('<img align="absmiddle" src="loading.gif"/> Checking availability...');
$.ajax(
{
type: "POST",
url:"regcheckuser.php",
data:"username="+usr,
success: function(msg)
{
$("#usernameStatus").ajaxComplete(function(event, request, settings)
{
if(msg=="OK")
{
$("#username").removeClass("object_error");
$("#username").addClass("object_ok");
$(this).html('<img align="absmiddle" src="checkmark.png"/>');
success=true;
}
else
{
$("#username").removeClass('object_ok');
$("#username").addClass("object_error");
$(this).html(msg);
success=false;
}
}
);
}
}
);
}
else
{
$("#usernameStatus").html("The username should have at least 7 characters");
$("#username").removeClass('object_ok');
$("#username").addClass("object_error");
success=false;
}
});
return success;
}
$(document).ready(function()
{
if(IsEmailValidAndNew() && IsUserAlreadyExist())
{
$('button').find("#signup").attr("disabled","false");
}
else
{
$('button').find("#signup").attr("disabled","true");
}
});
</script>
</div>
</body>
I use notepad to code it, it doesn't work and I can't find out the mistake. I don't know any good tool you might be using to code in javascript that has awesome options like an embedded intellisense and debug capability.
There are several problems with your code.
Your email regex is not thorough enough (OK, this isn't actually stopping the code working, but it's the first thing I noticed).
Your ajax calls are asynchronous, which is good, but means that the functions that do the $.ajax() calls will complete before the ajax response is received. You need to restructure this to do something from the ajax success callback.
You don't need the ajaxComplete() function - you're already within an ajax success handler at that point so put the code within your current ajaxComplete() directly in the containing success function.
You call IsEmailValidAndNew() and IsUserAlreadyExist() once from your document ready and disable or enable the "signup" control, but at no point after that do you re-enable or re-disable it. You are calling these functions as if they will validate the fields, but really what they do is set up change handlers on the fields so the code in the functions won't do anything until the fields actually get changed by the user.
Following is one way you could structure your code instead:
$(document).ready(function() {
var emailOK = false,
nameOK = false;
function setSubmitEnabling() {
$("#signup").prop("disabled", !(emailOK && nameOK));
}
setSubmitEnabling();
$("#username").change(function() {
var usr = $(this).val();
if (usr.length < 7) {
$("#usernameStatus").html("The username should have at least 7 characters");
$(this).removeClass('object_ok').addClass("object_error");
nameOK = false;
setSubmitEnabling();
} else {
// format seems OK, so do ajax call:
$("#usernameStatus").html('<img align="absmiddle" src="loading.gif"/> Checking availability...');
$.ajax({
type: "POST",
url:"regcheckuser.php",
data:"username="+usr,
success : function(msg) {
if(msg === "OK")
{
$("#username").removeClass("object_error")
.addClass("object_ok");
$("#usernameStatus").html('<img align="absmiddle" src="checkmark.png"/>');
nameOK = true;
}
else
{
$("#username").removeClass('object_ok')
.addClass("object_error");
$("#usernameStatus").html(msg);
nameOK = false;
}
// now update button state
setSubmitEnabling();
}
});
}
});
$("#memberemail").change(function() {
// basically the same thing as for the username field as shown above,
// except setting emailOK instead of nameOK, so I suggest you get the
// username part working first then come back to do this the same way
});
});
The idea of the above code is that there are several points where you need to enable or disable the "signup" button, and that depends on two unrelated conditions. So create a flag for each of those conditions, and function setSubmitEnabling() that checks the flags and enables or disables the buttons. Call that function immediately when the page loads to set the initial enable/disable state, and call it again any time something changes that needs the enable/disable state to be re-evaluated.
Also, create a change handler for each of your two fields. The change handlers will be similar to each other, basically doing some initial quick validation to see if the length and format is OK and if so an ajax call to test for uniqueness.

Categories