I have checked the user name availability. The problem is, even if the username is not available, the form is posting.
Edited Code:
<SCRIPT type="text/javascript">
$(document).ready(function(){
$("#emailch").change(function() {
var usr = $("#emailch").val();
if(usr.length >= 3)
{
$("#status").html('<img src="images/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "includes/check.php",
data: "username="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img src="images/tick.gif" align="absmiddle">');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>3</strong> characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
});
});
</SCRIPT>
What I want is that, the form should not be posted if the user name is not available. I have tried by using return false; in IF CONDITION but it fails. Please suggest any alternate method. Any help will be appreciated.
on submit return false no matter what, if the field is good do your ajax send of the form, if its bad, error out or whatever you need
<form action="http://www.google.com" id="formId" method="post">
<input type="text" id="emailch" name="emailch" />
<input type="submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#formId").submit( function() {
if( $("#emailch").val().length >= 3){
alert( 'the form is going to post via ajax here' );
}else{
alert( 'user name invalid error out or whatever you need to do.' );
}
return false;
});
});
</script>
Using return false to stop a form from being submitted doesn't really work that well in jQuery. Use event.preventDefault() instead, try something like this:
$(function() {
$('#formid').submit(function(event) {
if ($("#emailch").val().length < 3) {
event.preventDefault();
}
});
});
Set a flag (variable) in your success function to false (for instance) if the username is not available. Then check that flag in your form's onsubmit handler, and if the flag equals false, return false from that event handler, and your form will not submit.
Related
I've created a JQuery script that checks a database for usernames and shows an error if you type in an existing name on keyup, this is workng fine but the form still submits even if this error is true. What other code can I add to check that this error doesn't exist? Here is the code I have so far:
<script>
$(function()
{
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Thank you
please see the comments on the code
assuming that the data == 1 means that the name is already registered and you will show an error
<script>
$(function()
{
var name = false; // a variable that holds false as the initial value
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
name = true; // on success , if the name isnt there then assign it to true
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username) && name == true) // check for the value of name
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Instead of checking the username against the regex, you should check the status of $('.usernameStatus') because it is possible that it passes the regex test but still fails the duplicate test returned from your db.
So
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
should instead be:
$('#registerButton').click(function()
{
var username=$("#username").val();
if(!$('.usernameStatus').hasClass('error'))
{
Even better would be to introduce a variable that holds the validity of the name field so you don't need to get the DOM Element all the time and check it's class.
I think your error might be because of a bad data syntax
It should be like this:
data: 'username:'+ username,
Debug your PHP code to see if its receiving the username properly at the moment though
I have a problem with ajax/php script.
It is for checking Username avaibility for user registration.
javascript
$(document).ready(function()
{
$("#username").change(function()
{
var usr = $("#username").val();
if(usr.length >= 4)
{
$("#status").html('<img src="./style/images/loading.gif"> Checking availability...');
$.ajax(
{
type: "POST",
url: "./ps/ajax_validation.php",
data: "username="+ usr,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
$(this).html(' <img src="./style/images/tick.gif" align="absmiddle">');
}
else
{
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
}
});
});
html
...
<input class="login_reg_field" id="username" name="username" type="text" value="<?php echo #$d['username']?>" />
<div id="status"></div>
...
ajax_validation.php
<?php
include("../core/config.php");
if(isset($_POST['username'])){
$username = $_POST['username'];
$test = $user->checkUsernameAvaible($username); //Return True if Username IS Avaible
if(!$test){
echo '<font color="red">The nickname <STRONG>'.$username.'</STRONG> is already in use.</font>';
}else{
echo "OK";
}
}
?>
The php script is working, i tried it manually with $_GET variables..
When trying on the form, it stay on Checking avaibility... and No Javascript error on Firefox Console.
Also i've checked with Tamper Data, that the ajax request it's being made, and it is.
The problem seems to be on $("#status").ajaxComplete(function(event, request, settings){ because i've tried with an alert after this line, and no alert popping up.
update..
success is called whn the ajax call succeeds. so ther eis no need to call ajaxComplete there.. (if u think there is the problem)..
success
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
you can just check the response data and do your stuff..
success: function(msg){
if(msg == 'OK')
{
$(this).html(' <img src="./style/images/tick.gif" align="absmiddle">');
}
else
{
$(this).html(msg);
}
}
i think the problem is here
$("#username").change(function()
{
change() on input text fires only when you click somewhere outside the input field.. //try it once.
what you need is keyup()
$("#username").keyup(function()
{
Ok Answering my own question, i've solved.
Want to thank itachi for letting me know to use .done instead of success:
The problem was there.
Here is the revised and working part of the script:
var req = $.ajax(
{
type: "POST",
url: "./ps/ajax_validation.php",
data: "username="+ usr,
}).done(function(msg)
{
if(msg == 'OK')
{
$("#status").html(' <img src="./style/images/tick.gif" align="absmiddle">');
}
else
{
$("#status").html(msg);
}
});
I'm validating an initially hidden form using jquery, but the form is submitted even though the fields are empty
$(document).ready(function () {
jQuery("#name").validate({
expression: "if (VAL) return true; else return false;",
message: "* Please enter name"
});
});
I'm doing this for ajax submition of the form ..
$("#send").click(function (e) {
e.preventDefault();
var name = $('#name').val();
$.ajax({
// ajax submition
)};
});
Try this... and use the <form> id instead for the validate function.
$(document).ready(function () {
jQuery("#formid").validate({
ignore:'',
rules:{
name:{
required:true
}
},
messages:{
name:{
required:'* Please enter name'
}
}
});
});
I think you are using the newer version of jQuery validator plugin which ignores hidden elements by default.
In reply to your updated question you can just do this
$("#send").click(function (e) {
e.preventDefault();
var name = $('#name').val();
if(name.length > 0){ //if length is greater than 0 then only fire ajax else show the error
$.ajax({
// ajax submition
)};
}else
//show error
alert('Name not found');
}
}
i am trying to prevent the form from executing if the search field is blank.
html
<form id="form" action="">
<input type="text" id="lookup"><input type="submit" id="find" value="Look Up">
</form>
jquery
$('#find').click(function(){
var s = ('#lookup').attr('value');
if(s!=""){
$.ajax({
url: result/,
type:'POST',
data: s
success: function(){ //empty }
});
}
});
also tried
action="result" //form the form
$('#find').click(function(){
var s = ('#lookup').attr('value');
if(s!=""){
$("#form").submit();
}
});
Bind the submit event, and return false when the search field is blank, and true if it isn't. Returning false will prevent the form from being submitted.
$("form").submit(function() {
var s = $.trim($('#lookup').val());
if (s) {
$.ajax();
return true;
}
return false;
});
DEMO.
you can simple add do this
$('#find').click(function(){
var s = ('#lookup').attr('value');
if(s==""){
return false;
}
});
$('#find').click(function(e){
var s = ('#lookup').attr('value');
if(s!=""){
$.ajax({
url: result/,
type:'POST',
data: s
success: function(){ //empty }
});
}
e.preventDefault();
});
e.preventDefault() will stop submit button from actually submitting a form. Or you can use return false.
But suppose in your case it will be enough to do something like:
$('#find').click(function(e){
var s = ('#lookup').attr('value');
if(s==""){
e.preventDefault();
}
});
try
$('#find').click(function(){
var s = ('#lookup').val();
if(s!="" && s != undefined && s!=null){
//do your business here
}
});
The Question is pretty direct. I have two variables in JS. I want to pass these to a php file first to update a database, and then return back to the original file, a true or false value based on the query. How do i do this?
Consider the PHP file for checking existing username as:
<?php
if(mysql_num_rows(mysql_query($query)) === 1)
die('true');
else
die('false');
?>
In your HTML File, you can call this way (using jQuery):
<script type="text/javascript">
function checkUsername()
{
$.ajax({
url: 'checkuser.php?username' = $('#username').val(),
success: function(data) {
if(data == 'true')
alert('Username Available!'); // User Exists!
else
alert('Username not Available!'); // User not Exist!
}
});
}
</script>
And in HTML:
<input type="text" name="username" id="username" />
Check
Hope this helps! :)
HTML
<'input type = "TEXT" Id="TEXTTOPARSE">
<'Span id="ResultVAlue>
On Load of the Page
$(document).ready(function(){
$('#TEXTTOPARSE').bind('onChange', function(){
var val = $(this).val();
updatePage(val);
});
});
function updatePage(value){
$.ajax({
method:"POST",
url:"YourPageLink"
data:{"textValue" : value},
success: function(data){
$('#ResultVAlue').html(data);
}
});
}