I'm developing a website, and right now the registration form of it! But I have something like a problem! I want to create a Username input field, and when the user is typing, check if the username already exists in the database and give some output.
The error is this one: suppose that in the database there is only the username "Manuel". If I type "Manuel" in the input field no message is shown. Now if I type any other character it gives me the message 'The user already exists'. If i delete the last typed character the message goes away. If I type again and have something like "Manuela", the message shows up, if I type again and have "Manuelae" the message goes away
Thanks for your help!!
Here the code
Here the input field: (register.php)
<input type="text" id="username" name="username" maxlength="40" required="required">
<span id="username-info">What's your username?</span>
Here the javascript and jquery code (registration.js)
$(document).ready(function () {
var userExists = new Boolean();
var username = $("#username");
var usernameInfo = $("#username-info");
username.keyup(validateUsername);
}
Here the function validateUsername():
function validateUsername(){
checkUsername();
var minlenght = 5;
var usernameVal = username.val();
if(usernameVal.length < 1){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.FIELD_REQUIRED);
} else if(usernameVal.length < minlenght){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.USERNAME_MIN_WORDS+minlenght+' '+messages.USERNAME_CHARACTERS);
} else if(userExists){
//here i tell the user that the user already exists
usernameInfo.addClass("input-error");
usernameInfo.text('The user already exists');
} else {
usernameInfo.removeClass("input-error");
usernameInfo.text("");
}
}
And here the function checkUsername():
function checkUsername() {
var url = 'processregistration.inc.php';
$.ajax({
type: "POST",
dataType:"json",
url: url,
data: {username: username.val()},
success: function(data){
userExists = data.CHECK; //true if the user exists, false if not
}
});
}
Ajax means Asynchronous JavaScript and XML.
You are doing a check on a value which is actually not received.
You should do something like this :
function validateUsername() {
// remove input-error, text
if (...localcheck...) {
// add input-error, text
}
else if (...otherlocalcheck...) {
// add input-error, text
}
else {
$.ajax({
...
success : function(data) {
if (data.CHECK) {
// add input-error, text
}
}
});
}
}
I think you are on the right track, but I don't think your implementation is correct.
Note: I'm not a javascript hero
$("#filter").keyup( function(e) {
var filter = $("#filter").val(),
timer = $('#filter').data('timeout'),
if(timer) {
clearTimeout(timer);
$('#username').removeData('timeout');
}
$('#username').data('timeout', setTimeout(function() {
var url = 'processregistration.inc.php';
$.POST(url, {username: $('#username').val()}, function(data) {
// you get the picture ;)
updateComponentThatShowsIfUserNameIsTakenFunction(data.CHECK);
});
}, 100));
function updateComponentThatShowsIfUserNameIsTakenFunction(taken) {
$('#username').addClass('input_error');
}
What I did: Removed global variables, they are annoying and error prone. Instead, I'm using a callback named updateComponentThatShowsIfUserNameIsTakenFunction. You can also change it to directly call that function with the "data" of course. I have also added a timeout for you so that you won't call the server EVERY key-up. Every key-up cancels the previous timeout, causing the check to only trigger 100ms after the user is done typing (you don't want to spam your server).
I hope this works and helps you further!
Related
I'm dealing with a difficult problem concerning asynchronous calls:
A JQuery function executes on user click, it then calls for a php file to check is the user input will overlap with information already in the database.
If it does, the user then should be prompted for confirmation if he wants to proceed anyway or cancel, if he clicks ok, then it executes another call to write data in the database.
The structure I was thinking is something like
User clicks button:
Ajax -> Success: true or false.
If True -> User is prompted -> It overlaps, want to proceed?
If Yes -> Ajax -> Write stuff on database.
The problem is, I couldn't find a single solution that would let me do this.
Any help is appreciated!
Javascript
$.ajax({
type: "POST",
url: 'your_url.php',
data: your_data
})
.success(handleResponse);
function handleResponse(data) {
if (data.request_overide) {
if (confirm('There is an overlap... Proceed?')) {
data.force = true;
$.ajax({
type: "POST",
url: 'your_url.php',
data: your_data
})
.success(handleResponse);
}
} else {
alert('Successfully added!')
}
}
PHP - your_url.php
$duplicate = false;
//Check if duplicate
if(!$_POST['force']){
$duplicate = somecheck();
}
if(!$duplicate){
addData();
}
echo json_encode(['request_overide' => $duplicate]);
Method using jQuery.post():
/* check if the user input will overlap with information already in the database */
$.post('/path/to/check-database.php', dataObject, function(response) {
/* If it does - because JavaScript treats 0 as loosely equal to false (i.e. 0 == false) */
if(response != false) {
/* the user then should be prompted for confirmation if he wants to proceed anyway or cancel */
if(!confirm('It overlaps, want to proceed?')) { return false; } // cancels
}
/* Write stuff on database */
$.post('/path/to/update-database.php', dataObject);
});
Basically, you POST into your check PHP script and it returns either 1 (true) or 0 (false). If it's true, you confirm your user wants to continue. If they click cancel, it will exit the function. If they confirm or the script returns false, it will execute the second POST into your update PHP script.
$.ajax({
type: 'POST',
data: { input: 'someInput' },
success: function(response) {
if (response.confirmation == 1)
//Do prompt
if (promptisSuccessful) {
//Do a second Ajax call
}
}
});
Your php code should return a json response, something like
{confirmation:1} if validation or logic passes and {confirmation:0} if it fails.
Hope it helps
I have a form with AJAX submit.
This form is working, but I have the impression that the functions are not correct.
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
I think that has a lot of wrong code, for example:
if(dados == "email=") // >>> This field, how to check if the field is blank?
and >>
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
I tried to update but not return any results
Test Code
//if (email.val() == "")
//{
//email.focus();
alert(email.val()); // op1
alert(dados); // op2
alert($.trim($('email').val())); // op3
emailInfo.html("<font color='red'>Required.</font>");
return false;
//}
if insert an email, the only option that returns is op2 email=teste#teste.com
I think your code is trying to validate email by ajax before submitting form. If so this code seems ok to me out of a few points.
return false at the end of submit call may not work on firefox. Use e.preventDefault();. Look at this post. If you try this code on chrome it may fail beacuse you have no return true anywhere.
Your second code block is ok. email.val(data); is equal to $("#email").val(data);. I think you are trying to set the email input value to the result.
if(dados == "email=") can be changed to if (email.val() != ''). So you wont need to dados also.
You don't use myForm variable nowhere. It should be deleted.
If validating the email on server side is not a must think about validating on client side.
The returned data value is echoed from your PHP file. There are two approaches to take to validate your data:
Do it in the frontend with JS prior to sending your form.
Do it with your PHP code in the separate file.
email.val(data); // This field, how to display the data
sent in the email field? not the return of PHP
I am guessing that you want to ensure that the value doesn't get deleted if the user sends an invalid request (thus having to type the value in again).
What you can do is store the values of what the user has entered on form submit but prior to sending the AJAX request: var emailVal = email.val();
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
var emailVal = email.val(); // Assign the entered input to an emailVal variable
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(emailVal); // Store the entered value back into the email input
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
Another Note
I would also like to point out this: if(data == "invalid")
I have found that PHP can send back error messages within the data along with whatever you ask it to return. If you have any error in your PHP code, this will never hit because invalid will never be the only string of characters in the returned data value. To protect yourself, I would do either two things:
Return an HTTP error and do error handling within the error callback of the AJAX function: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Return a unique word and search for that word within the returned data string:
PHP
if(!validEmailCheck($email)){
echo('invalidRAWR');
}
JS
if(data.indexOf('invalidRAWR') != -1) // Built in PHP errors will never return 'invalidRAWR'
I have this login button where i click it will check on database whether the user match the pw, then it will return from php the result either true/false/nothing.
My issue is that when i use .on function and log in, then i logged out, and i log in again it will run twice, login and log out again and it will run thrice, basically a auto increment of one more running times per cycle.
To avoid that i tried .one function, but this is only effective if i am sure to login succesfully, but if i typed a wrong password it will stayed at the same page and i can't click on the login button anymore as i'm using .one function, so i am trying to check if there is anyway if the php return false/nothing i can add a call to reset .one back to 0?
This is my code
$("body").on("pageshow", "#p-login",function(){
$(this).one("click","#btn-signUp", function(){
$.mobile.changePage($("#p-signUp"), "slide", true, true);
});
$(this).on("click","#btn-logIn", function(){
var username = $("#login-username").val(); // store input val into var
var password = $("#login-password").val();
$.post("login.php",
{
username:username, // data to pass into php
password:password, // data to pass into php
}, // data to pass into php
function(response)
{
if(response.type == "true")
{
console.log(response);
globalUsername = response.username;
$.mobile.changePage($("#p-home"), "slide", true, true);
console.log(globalUsername);
}
else if(response.type == "false")
{
console.log(response);
//alert("Password enter incorrectly, please try again.");
}
else if(response.type == "nothing")
{
console.log(response);
//alert("User is not found in database, please try again");
}
}, 'json'
);
});
});
I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)
When i use blur function on textbox to check duplicate name using jquery ajax working fine.
Here is code:
function duplicate(data){
//alert(data); //successfully gives the value from the text input
$.post("test.php", {name: data}, function (data){
if(data){
alert('duplicate name');
}
});
}
$(function() {
$("#name").blur(function(){
var data = $("#name").val();
duplicate(data);
});
});
The problem is it show alert message, in some case we submit with duplicate name itself so there is no use of checking duplication.
Let me know the solution to check duplicate name using onsubmit function ( jquery ajax or javascript ).
Your question is confusing because you're using the same variable name, data, outside of your request as well as in the request callback.
I'm not sure if you're asking to check for duplication based on data that has already been submitted and is back on the page, data that exists on the server, or if the data's simply "yes".
Based on the code you provided, it would appear that data is considered to be duplicated if the server returns yes once the POST completes.
Either way, maybe this will help:
$(function() {
$('#name').blur(function() {
duplicate($('#name').val());
});
});
function duplicate(sData) {
var sDuplicateValue = ...; // assign this whatever constitutes a duplicate value
if(isDataDuplicate(sData, sDuplicateValue)) {
// you have duplicate data
}
$.post('test.php', { name: sData }, function(sResposeData) {
/* because of question ambiguity, i don't know if you want to compare
* sData and sResponseData, or sResponseData and "yes." if it's the latter,
* just do isDataDuplicate(sResponseData, "yes"); otherwise, do this:
*/
if(isDataDuplicate(sData, sResponseData) {
// it's the same..
}
});
}
function isDataDuplicate(sData, sDuplicateValue) {
if(sDuplicateValue === null) {
return sData === 'yes';
} else {
return sData === sDuplicateValue;
}
}
I'll do something like this:
$(function() {
$("#name").blur(function(){
var value = $("#name").val();
$.post(
"checkDuplicates.php",
{ name: value},
function (data){
if( data.response === 'yes'){
$("#name").css({
'border': '1px red solid'
}).parent().append('This name already exists');
} else {
return false;
}
},
'json'
);
});
});