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);
}
});
Related
I have Jquery/Ajax Code which sends Text Fields Data to PHP Script. But i don't know how i can receive that data and process for Validation.
Here is the Ajax Code:
$("#button").click(function (e) {
var dataa = $("#survay").serialize();
var data = $("#yourName ,#emailAdress , #phoneNumber , #zipCode").serialize();
$.ajax({
type: "POST",
url: 'processRequest.php',
data: dataa,
beforeSend : function(){
$('.eDis').empty().append('<div class="loader"><img src="images/32.gif" /> Loading...</div>').show();
},
success: function (html) {
if(html !='1') {
$('.eDis').empty().append(html).addClass("actEr");
setTimeout(function(){
$('.eDis').removeClass("actEr")}, 5000);
}
if(html == '1') {
$('.eDis').empty().append('<div class="success">Your Message has been sent</div>').addClass("actEr");
window.location ='../thank-you.html';
}
if(html =='0') { $('.eDis').empty().append('Error..').addClass("actEr"); setTimeout(function(){
$('.eDis').removeClass("actEr")}, 3000);
}}
});
});
processRequest.php should be PHP script which will handle all the texts fields data.
If above Text fields data is valid then i want it to Proceed further and redirect the page to thank-you.html
.eDis is CSS class, which i want to use to display valid,Invalid fields information.
It is in HTML.
Based on your information, I can't give you exact code, but, this is what you can do:
<?php
if(isset($_POST['itemName']) && isset($_POST['anotherItemName']) /* ...and so on */){
if($_POST['itemName'] == $validSomething)
echo 'WOW!';
}
else
echo 'error';
?>
What you are "echoing" is what you get in "success" data in your javascript.
I am also having problem with this that it always results into 'Username already taken'. how can i fix this thing? I need that ajax loader animation to run for 4seconds and then give the user any message
<script type="text/javascript">
$(document).ready(function() {
$("#username").change(function() {
$("#message").html("<img src='ajax-loader.gif' /> checking...");
var username = $("#username").val();
$.ajax({
type: "post",
url: "sign_up.php",
data: "username=" + username,
success:function(data) {
if(data == 0){
$("#message").html("<img src='tick.png' /> Username available");
} else {
$("#message").html("<img src='cross.png' /> Username already taken");
}
}
});
});
});
</script>
there is error in your ajax call it should be as follow
$.ajax({
url: "sign_up.php",
data: {'username': username},
type: "POST",
success: function(data) {
if(data == 0) {
$("#message").html("<img src='tick.png' /> Username available");
} else {
$("#message").html("<img src='cross.png' /> Username already taken");
}
}
});
on sign up page you can access username by $_POST['username']
Use setTimeout before sending ajax request.
setTimeout(function() {
// Just Pass
}, 4000);
This will ensure that request must be executed after 4 seconds.
You can use setTimeout function. For example following code will hide div after 3 seconds
jQuery(document).ready(function () {
//hide a div after 3 seconds
setTimeout( "jQuery('#div').hide();",3000 );
});
I would probably use the setTimeOut() function, that works like this:
setTimeout(function() {
// any script here will execute after 2 seconds
}, 2000);
Here the code will execute after 2 seconds.
Hope this helps.
By using setTimeout() within the success function, you can delay your response message. I also changed your data assignment to an object, this is better because jQuery will encode the value for you. If you pass a string of data like in your original code, you are responsible for the encoding and you need to wrap it in encodeURIComponent().
$.ajax({
type: "post",
url: "sign_up.php",
data: {username : username},
success:function(data){
setTimeout(function(){
var msg = data == 0 ? "<img src='tick.png' /> Username available" : "<img src='cross.png' /> Username already taken";
$("#message").html(msg);
}, 4000);
}
}
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 was trying to validate username whether exist or not with the following code. But it somehow don't work to prevent the existing username.
**NOTE: checkusr2.php is a simple php to check wheter the username in database.
function verifyUser() {
var usr = $("#username").val();
$.ajax( {
type: "POST",
url: "checkusr2.php",
data: "username="+ usr,
success: function(msg) {
$("#txtHint").ajaxComplete(function(event, request, settings){
FormErrors = false;
if(msg == 'OK') {
FormErrors = true;
$('#formElem').data('username',FormErrors);
} else {
$('#formElem').data('username',FormErrors);
}
});
}
});
}
/** calling the function to check. **/
verifyUser();
if($('#formElem').data('username')){
alert('Username exist, please try another username.');
return false;
}
Use an http proxy like Charles, Fiddler, WireShark, etc... to view the ajax request you are sending and verify that the response is what you expect.
For one thing, you are making an asynchronous call (the A in Ajax) to get the response for whether the username exists. The check, immediately after the verifyUser call is being called as soon as you call the verifyUser and the the request to checkusr2.php may or may not have actually returned by then.
I have also never seen the ajaxComplete set inside of the success handler. I think you may want to change it like this:
function verifyUser() {
var usr = $("#username").val();
$.ajax( {
type: "POST",
url: "checkusr2.php",
data: "username="+ usr,
success: function(msg) {
if(msg != 'OK') {
alert('Username exists, please try another username.');
$("#username").val("");
}
};
});
}
Your problem is in trying to use verifyUser synchronously. The code seems fairly sound, the problem is that $.ajax executes asynchronously using XMLHTTPRequest. This means that your code immediately following the call to verifyUser cannot depend on the side effect of its completion.
What you need to do is run the verifyUser callback earlier (like, say, when the user un-focuses the username field), so that when it comes time to submit you've already got the result.
For example:
$('#username').blur(function() { verifyUser() });
A further change would be instead of preventing submit, you can make verifyUser show a div with a message next to the field when the username is invalid. You'd make these changes to your handler:
if(msg == 'OK') {
FormErrors = true;
$('#username_invalid').show();
} else {
$('#username_invalid').hide();
}
Then you could show the user the username cannot be chosen immediately, without wasting their time submitting it.
Try this
$("#txtHint").ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html' && xhr.responseHTML=="Ok") {
FormErrors = true;
$('#formElem').data('username',FormErrors);
} else {
$('#formElem').data('username',FormErrors);
}
})
Thanks for bringing up this .ajaxComplete() that I didn't know about. I think it will be of great help for me in the future.
But anyway I don't think it's what you want to use in this specific case:
function verifyUser() {
var usr = $("#username").val();
$.ajax( {
type: "POST",
url: "checkusr2.php",
data: {'username':usr},
success: function(msg) {
if ( msg != 'OK' ) {
alert('Username exist, please try another username.');
return false;
}
});
});
}
The function that you want to execute after the Ajax call must be passed as a callback of the Ajax function, otherwise, and even if you put it after your Ajax function, it will execute before the server's response.
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.