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'
);
});
});
Related
The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.
We include the jQuery library page
JQuery add an event that no longer do submit the form
Added an event with jQuery , when making submit to execute ajax
Depending on the message came to Ajax , whether to show success or failure
This is all greatly simplified but on the javascript side, you could do this:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
and on the php server side, your server.php could look like this:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>
function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});
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'
when i enter the wrong details and run it. it pops up with the error message, but if i then enter the correct details and click run it again. the sign in button changes to "Connecting..." as it should but then nothing else happens
$(document).ready(function() {
var width = ( $(".main").width() - 5);
if (width < 300) {
$(".logo-img").css({"width":width});
};
$("#error").hide();
$(function() {
$('#login').on('click', function(e){
e.preventDefault();
var token = $('#token').val();
var username = $('#username').val();
var password = $('#password').val();
var remember = $('#remember:checked').val();
$.ajax({
url: 'core/functions/ajaxLogin.php',
method: 'POST',
data: { 'username' : username,
'password' : password,
'remember' : remember,
'token' : token },
dataType: 'html',
cache: false,
beforeSend: function() { $('#login').val('Connecting...') },
success: function( data ) {
if (data == 'success') {
setTimeout( "window.location.href='backorderbook';", 500 );
} else if( data == 'userorpass' ) {
$('#error').fadeIn();
$('#error_message')
.html('username or password were entered incorrectly');
$('#error').delay(3500).fadeOut();
$('#login').val('Sign In');
};
}
});
});
});
});
Reason behind working once.
when your ajax fired, first thing to do is show connecting.. then when you get response which is data your statement says
if data == success //redirects
elseif data == userpass //show you have invalid username/password and clear html
So what if your data is not succes / userpass
it will just run your ajax beforeSend() and not will remove connecting that seems to you running once.
I recommend that your data should be an object and check if there's an error with the message on it , in short have it on your backend and just jquery show that message
There is a token generated when the login page is loaded and sent with the Ajax. But my PHP token system doesn't like the same token being sent over and over and blocks the request.
run your function with Fiddler .. and/or add the error parameter to your ajax... odds are your web request isn't a success.
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!
I have email field in user's settings area. All emails are unique, of course, so I need to check is email not used already by someone else before submitting the form.
Here is the code:
var email = $("input#email-id").val();
$("#form-id").submit(function(){
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
}
});
});
So, if data is not 'ok' it must destroy submitting the form because if() returns false, but it doesn't and the form submits as usual and even alert doesn't appear!
I've checked ajax answer and it works fine (returns 'user_already' if email is used).
So what I did wrong?
Thanks!
Since ajax is async by nature you cannot do that. If you really want to do that you can submit the form inside the success handler. Try this.
function submitHandler(){
var email = $("input#email-id").val();
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
else{
//Once the data is ok you can unbind the submit handler and
//then submit the form so that the handler is not called this time
$("#form-id").unbind('submit').submit();
}
}
});
return false;//This will prevent the form to submit
}
$("#form-id").submit(submitHandler);
It's because the Ajax request to check the email is asynchronous. It will not complete before the submit event handler is finished. You'd have to do something like this:
$('#form-id').submit(function() {
if($(this).data('valid')) {
//you've already validated, allow the form to submit
return true;
} else {
//send an ajax request and wait for the response to really submit
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data == 'ok') {
//submit the form again, but set valid data so you don't do another Ajax request
$('#form-id').data('valid', true);
$('#form-id').submit();
} else {
alert("Email is used already");
}
}
});
return false;
}
//clear the validation flat
$(this).data('valid', false);
});
There's an accepted answer but I thought I'd share another way to do this.
You can use an extra parameter with the .trigger() function to first test the user's email, and if it comes back available then re-trigger the submit event but set a flag to not check the username:
$("#form-id").submit(function(event, forceSubmit){
//the normal submit will not have the extra parameter so we need to initialize it to not throw any errors,
//typeof is great for this since it always returns a string
if (typeof(forceSubmit) == 'undefined') { forceSubmit = false; }
//now check if this is a normal submit or flagged to allow submission
if (forceSubmit === false) {
var $form = $(this);
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
} else {
$form.trigger('submit', true);
}
}
});
//since this submit event is for checking the username's availability we return false to basically: event.preventDefault(); event.stopPropagation();
return false;
}
});
.trigger(): http://api.jquery.com/trigger
In your code you have two functions. One is the function passed to submit:
$("#form-id").submit(function() {
// code
});
The other is the function passed to the success handler of the AJAX call:
success: function(data) {
// code
}
You are returning false from the second function. This means that when the first function returns, it is not returning false. But the form submission is stopped, only if the first function returns false.
What you should do is to make the function passed to submit always return false and handle submission programmatically.
This code helps you to achieve this:
var submitHandler = function() {
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data) {
if (data != 'ok') {
alert("Email is used already");
// no need to do anything here
} else {
// success, we should submit the form programmatically
// first we de-attach the handler, so that submitHandler won't be called again
// and then we submit
$("#form-id").unbind('submit').submit();
// now we reattach the handler, so that submit handler is executed if the user
// submits the form again
$("#form-id").submit(submitHandler);
}
}
});
// always return false, because if validation succeeds, we will submit the
// form using JavaScript
return false;
};
$("#form-id").submit(submitHandler);
I already +1 #ShankarSangoli because he got it right however, I don't feel its 100% complete as there is also an error state that can occur upon network issues or server fault.
$('#form-id').submit(function(ev) {
ev.preventDefault(); // cancels event in jQuery typical fashion
$.ajax({
url: "/ajax/email",
data : { email: $("input#email-id").val()},
success : function(d) {
if (d !== 'ok') {
alert('email in use');
}
},
error : function(a,b,c) {
// put your error handling here
alert('a connection error occured');
}
});
});
There are even better ways to handle this as I've written some great form plugins for jQuery that are HTML5 compliant and rival jQuery tools for ease of use.
You can see an example here -> http://www.zipstory.com/signup
Happy coding.
If JSON is involved, the returned data is in data.d - see http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ for an explanation.