Check if username already exists - only working with onclick - javascript

I'm trying to check if username and email already exist on a register page.
I've got this javascript code:
var nombre = document.getElementById("username").value;
var email = document.getElementById("email").value;
var errorNombre = document.getElementById("erno");
var errorEmail = document.getElementById("erem");
if (nombre == null || nombre.length == 0 || /^\s+$/.test(nombre)) {
errorNombre.innerHTML = "<font color='red' face='century gothic'>Debe introducir un nombre de usuario</font>";
return false;
} else {
$.ajax({
type: 'POST',
data: {
email: email
},
url: 'consulta5.php',
success: function (response) {
if (response != 0) {
errorEmail.innerHTML = "<font color='red' face='century gothic'>Correo ya registrado</font>";
return false;
} else if (response == 0) {
//desde aquí
errorEmail.innerHTML = "";
$.ajax({
type: 'POST',
data: {
nombre: nombre
},
url: 'consulta4.php',
success: function (response) {
if (response != 0) {
errorNombre.innerHTML = "<font color='red' face='century gothic'>Nombre de usuario no disponible</font>";
return false;
}
}
});
}
}
});
}
And it works perfectly if it's part of a $( "#enviar" ).live("click", function(){, but tha problem is that this way the form is not sended if everything's ok. However, if I try to use the on submit = "return validate ()" only the first part of the javascript works, and the form is sended whenever the mail exists or not (but not when there are some blank spaces).
I'd really appreciate some help, because I don't have any idea on how to make this work!!
thanks :)

The form is not submitted because you never tell it to be. If, however, you change your innermost success function to something like:
success: function (response) {
if (response != 0) {
errorNombre.innerHTML = "<font color='red' face='century gothic'>Nombre de usuario no disponible</font>";
return false;
}
else {
$("#yourForm").submit();
}
}
then I believe your logic will be sound.
That said, there are some other changes I would recommend.
First, consider reworking your validation php to check both fields (name and email) in a single call. You can use a single response value to indicate which (if any) failed. If you want numeric response codes, then you could do something as simple as 0 for all's well, 1 for bad email, 2 for bad name, 3 for errors in both. There's really no need to be making two sequential trips to validate data that has no interdependencies.
Second, consider using CSS! There's no need to be using <font> here. Put a style (if you must) or a class (preferable) on errorNombre and errorEmail. If there are multiple errors that might be shown in those places, then just set the error text dynamically. If these are the only errors that go there, you don't even need that - put the error message in your HTML, and just dynamically show or hide the element.

Related

Syntax error, unrecognized expression on ajax call

I am working on a project where i have an issue with the commenting function i've made. Whenever i comment and use special characters the console displays this error: syntax error, unrecognized expression. Furthermore the request goes through and my backend (PHP) inserts the data to the DB but i then have to refresh to get the updated version of the post with that new comment. I can't figure out why even after a couple of searches here on stack and i could really use a new pair of eyes on the code.
I figure that the backend isn't the issue which is why it's left out of this post. Furthermore the form just contains a text input and a submit button. It might be important to mention that i use jQuery v3.3.1.
Finally when the form is submitted an ajax call gets triggered. Here it is:
var newComment;
$(document).on("submit", "form[data-comment]", function(e){
e.preventDefault();
var where = $(this);
var updateThis = $(where).parent().parent();
var data = $(where).attr("data-comment").split(",");
var comment = $(where).find("input[name='commenter']").val().toString();// <= this might be the issue?
if (data[0] == 1){
if (data[1] != "" && data[2] != "" && data[3] != ""){
//insert comment via ajax and return post and insert post
if (newComment){ <= prevent firing until newComment = false
newComment.abort();
return false;
}
$(where).find("input[type='submit']").prop("disabled", true);
$(where).find("input[type='submit']").val("commenting...");
newComment = $.ajax({
url: "mypage/core/AjaxRequests.php", <= call to php handler
type: "POST",
data: { type: "15", data: data, comment: comment }
});
$(comment).val("");
newComment.done(function(response, textStatus, jqXHR){
newComment = false;
$(where).find("input[type='submit']").prop("disabled", false);
$(where).find("input[type='submit']").val("Comment");
if (response.length > 200){
$(updateThis).parent().fadeTo(0,0);
$(updateThis).parent().prop('outerHTML', response);
$(updateThis).parent().fadeTo(1,1);
}
});
}
}
});

My jQuery working but callback is not working on the first time

I am working on a simple project to learn jQuery. My problem is after clicking the button, I call a jquery. It works and carries data to the controller but success function is not working at first click. It works on the second click properly. With my parameters, in these two calls, the method in controller returns true. but at first call, jquery does not running in the success function, but second call does.
Here is my jquery:
function signin() {
var parameters = {
email: $('#emailtxt').val(),
password: $('#passwordtxt').val()
};
console.log(parameters);
$.ajax({
url: '#Url.Action("Login","Session")',
type: 'GET',
data: parameters,
dataType: 'json',
success: function (correctData) {
if (JSON.parse(correctData) == false) {
alert("Incorrect e-mail or password.");
} else if (JSON.parse(correctData) == true) {
window.location.assign('#Url.Action("Index","Home")');
}
}
});
};
Here is my codes in controller:
public JsonResult Login(string email, string password)
{
using (var context= new ProjistDbContext())
{
var user = context.Users.FirstOrDefault(x => x.UserEmail == email && x.UserPassword == password);
if (user == null)
{
var result = JsonConvert.SerializeObject(false);
return Json(result, JsonRequestBehavior.AllowGet);
}
else
{
Session["UserId"] = user.Id;
var result = JsonConvert.SerializeObject(true);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
I kindly ask for your help in this issue. Thank you so much.
I solved my problem and I wanted to share it. The problem was caused because of that...
I was adding button like;
<button>...</button>
This kind of definition was refreshing page and it was causing error while getting response from controller. It also gave error sometimes like
XHR failed loading GET...
If I add type="button" to html button definition, it stops to refresh page and all posts and responses works good.
I would like to share the solution. Thank you all for your assistance.

Display the following AJAX in a blank/new page

I want to display the part which comes with the AJAX code in a new or blank page, without getting the requested url under the "old" html code on the same page.
d$(document).ready(function() {
$("#bestello").submit(function() {
if($("#nn").val() == "" || $("#vn").val() == "" || $("#strt").val() == ""){
$("#response").html("Bitte füllen Sie alle Felder aus!");
} else {
$.ajax({
type: "POST",
url: "test.php",
data: "nn=" + $("#nn").val() + "&vn=" + $("#vn").val() + "&strt=" + $("#strt").val(),
success: function(msg)
{
$("#response").html(msg);
}
});
}
return false;
});
});
Everything after the else or $.ajax({ should be displayed in a blank/new page.
How can I solve this problem?
You are looking for popup functions.
Place the following code inside your success function
var w = window.open('', '', 'width=400,height=400,resizeable,scrollbars');
w.document.write(msg);
w.document.close(); // needed for chrome and safari
Rather than submitting the form with ajax, allow the form to be submitted using its native functionality. Add the attributes target='_blank' action='test.php' method='post' to the form so that it will submit to test.php using post and open in a new tab/window.
You can still use javascript to validate the form. Your code would look like this:
$(document).ready(function() {
$("#bestello").submit(function() {
if($("#nn").val() == "" || $("#vn").val() == "" || $("#strt").val() == ""){
$("#response").html("Bitte füllen Sie alle Felder aus!");
return false;
}
return true;
});
});
This will validate the form with javascript and only allow it to submit if it passes validation. (As a side note, you should make sure that you do some server side validation as well).

Use AJAX and PHP to "Alert" the user if the username exists on the same page?

I have found many AJAX scripts that do a live check on if the username exists in a MySQL database. For example, most will maybe show a green check image if it does not exist or a red x if it does already exist.
I am interested in a slightly different method for this form.
Users fill out a 10 question quiz and then are taken to a user registration form. I only want to insert the user's answers into the database if they complete the quiz.
Currently, if a user enters a username or email that already exists, they will receive an error on the next page and be told to be go back only to find that the form has been reset.
That is why I want the information validated all on the same page.
Upon clicking the submit button, a javascript function is called that verifies a few things such as if the user has entered a date of birth, has not left a form blank, if passwords match, etc.
It returns false if any of the criteria is not met so that the form does move to the next page unless all of the functions return true.
Here is what it looks like.
function checkForm() {
if (checkUser() && checkPassword() && checkMonth() && checkDay() && checkAddress() && checkYear()) {
document.getElementById("quizForm").method="post";
document.getElementById("quizForm").action="register.php";
}
else {
return false;
}
}
I am interested in creating a username/email check function that uses ajax to access a php page that searches the database and returns true or false to javascript on if the username/email exists in the database.
That way, I can just use the old javascript alert to say if a username/email exists and then return false so that the form is not submit.
This is an example of how I am writing the functions for this:
function checkPassword() {
var pass1 = document.getElementById("pass").value;
var pass2 = document.getElementById("c_pass").value;
var pass1l = pass1.length;
if (pass1l < 5) {
alert("Please create a password that is longer than 5 characters.");
return false;
}
else {
if (pass1 != pass2) {
alert("Your passwords do not match.");
return false;
}
else {
return true;
}
}
}
Can anyone point me in the right direction for this? I have been searching around but have not found anything that is this specific.
Thank you.
You could AJAX Post on change event of the <input> where the user enters the username. Consider the example below I quickly put together. It assumes you have the database table users with columns id and username. It also assumes you have a file check.php connecting to this database table with a MySQLi connection in the variable $mysqli. When the input changes, it will call check.php, with the only data being the username entered. Depending on the response, it will update <span id="info">.
HTML:
<input id="username" type="text" /><span id="info">Exists/Does not exist</span>
Javascript(jQuery):
$(function() {
$("#username").on("change", function() {
var data = "user="+$("#username").val();
$.ajax({
type: 'POST',
url: 'check.php',
data: data,
dataType: 'json',
success: function(r)
{
if(r=="1")
{
//Exists
$("#info").html("Username already exists");
}else{
//Doesn't exist
$("#info").html("Username available!");
}
}
});
});
});
PHP(check.php):
$user = $_POST['user'];
if($stmt = $mysqli->prepare("SELECT id FROM users WHERE username = ?"))
{
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id);
$stmt->fetch();
if($stmt->num_rows>0)
{
echo "1";
}else{
echo "0";
}
}
I'm using similar functionality on my current project, and it works fine. Especially with local files as response time is improved!
(Reserved for typos, was in a rush-ish)
Hope this helped.

Return from jquery to javascript?

So I'm pretty new to Javascript and even newer to jQuery. Working on this project atm, I started with Javascript but a lot of the solution to my issues were a lot easier in jQuery.
so I have some javascript which basically prevents the user from pressing submit if all the forms have not passed validation.
So this is my field.
<td><input type="password" maxlength="16" name="passwd" id="passwd" onblur="validatePassword(this.value)" /></td>
<td><span id="pMess"></span></td>
This is my submit.
<td><input type="submit" value="Register" onclick="return validate(this.form)"/></td>
<td><a href='Index.php'>Login?</a></td>
As you can see when you press submit it goes to the validate function which is:
function validate(theForm) {
var valid = true;
if ( !validateEmail(theForm.emailrec.value) ) valid = false;
if ( !validatePassword(theForm.passwd.value) ) valid = false;
if ( !validatePostcode(theForm.postcode.value) ) valid = false;
if ( valid ) return true;
else return false;
}
And finally this is the field checker.
function validatePassword(passwordString) {
var valid = true;
if ( passwordString == "" ) {
feedback('pMess','Enter your password here');
valid = false;
} else if ( passwordString.length <= 5 ){
feedback('pMess','Password too short');
valid = false;
} else feedback('pMess','Acceptable');
if ( valid ) return true;
else return false;
}
My username field checker is slighty different as it's in jQuery
$(document).ready(function() {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if(username == "" || username.length < 6){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function(response){
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
so what I'm trying to do is get username_check to return like my other field checkers. I'm just looking for help as to where I should put the returns and stuff. Whatever I try seems to break the code...
All I have so far
if ( !check_username(theForm.username.value) ) valid = false;
Any help at pointing me in the right direction would be much appreciated.
The problem is not jQuery. The problem is that you are using an asynchronous call to do some of your validation. jQuery.ajax is asynchronous, meaning that code will continue to execute while it fetches check.php. In other words, by the time the response comes back, username_check() will have already returned and submitted your form (or cancelled the submit).
For the non-AJAX part of your code (the length check), you can do a return just fine:
function username_check() {
var username = $('#username').val();
// NOTE: This is redundant, as "" has length 0
if(username == "" || username.length < 6){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
$('#cross').fadeIn();
return false; // This will work here
} else {
// AJAX stuff
}
}
Unfortunately, the rest gets a bit more tricky. What you really want to do, is wait to sumbit your form until the username check is done, which means your submit needs to go in the callback function (i.e. the success part of your AJAX). If you only have one AJAX call, this is not too bad. If you have multiple AJAX calls, you need to either nest all of the calls (which makes the code take longer, is not very pretty, and will not easily proceed to other checks after one fails) or you need to use deferred objects (or something similar), which are not trivial (but very useful).
Assuming you have a single AJAX call for username:
First, add an ID to your submit button. This makes it easier to reference from jQuery:
<td><input id="mysubmit" type="submit" value="Register" onclick="return validate(this.form)"/></td>
<td><a href='Index.php'>Login?</a></td>
Secondly, do the username check after all of the other checks, and only submit if the other checks were valid:
function validate(theForm) {
var valid = true;
if ( !validateEmail(theForm.emailrec.value) ) valid = false;
if ( !validatePassword(theForm.passwd.value) ) valid = false;
if ( !validatePostcode(theForm.postcode.value) ) valid = false;
// The non-AJAX checks for username length:
var username = theForm.username.value;
if ( !validateUsername(username) ) valid = false;
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function(response){
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
// If the other checks were OK, submit the form manually
if(valid) {
$("#mysubmit").submit();
}
}
}
});
// ALWAYS return false.
// We will submit the form manually if the checks are OK
// For now, prevent the submit
return false;
}
Make sense?
Notes:
You probably want to disable the submit button after it is clicked (and re-enable it on failure. Otherwise, if the AJAX takes a while, a user could potentially change the field values before its callback, allowing bad data to be submitted without checks.
The other solution to this is to do the checks onsubmit. Currently, your checks are not called if the user pressed the enter key. This is bad!
Not sure if I follow, you want the function to return true or false if validates, right?
Edit: my code was crap, thanks roasted for pointing that out.
So, as you are doing an ajax call you can't really get if it's valid (true or false) in the same function, you probably need to do something different....
A couple of ideas;
-Use your DOM (add an "invalid" class or something like that to the form field and then check for that value.
-Use a global variable "valid_user" saving the result of the validation... ( i know global variables suck and it's a bad practice, but hey, if you have a deadline...)
then, when you are validating the hole form, check for this things instead of calling username_check again.
Hope this helps!

Categories

Resources