how to start another fuction in java script and ajax - javascript

I want to call another function after an ajax function finishes. After successful registration of a user, I want to have a callback function, but when I try, my sign up function stops working:
function signUp(){
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
}

EDIT your $(document).ready(function().. shouldn't be inside another function, because this way it will only get called when that function is called, and problably that is not what you intended, as i don't know how you use signUp() function i can't really tell.
You can use this way of making ajax request
function signUp(){
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.ajax({
type: "POST",
url: "http://localhost:5000/your/endpoint",
data: {
name1: name,
email1: email,
password1: password
},
success: function (data, status, xhr) {
// function called when it has succeeded
// Do what you want here in case of success
// The best way to do this should be used with statusCode because basically you
// only want to know that your post was OK.
},
statusCode: {
// Add more status code if you want to do something for each
200: function(){
$("form")[0].reset();
alert('You have Successfully Registered.....');
},
500: function(){
// In case of server error you should do something also
}
}
error: function(xhr, msg, err){
// Function called when error happens
}
})
}
});
});
}
You can even define functions to be called when a given status code is given as response, you can find the complete reference on http://api.jquery.com/jquery.ajax/

Related

Jetbrains PHPstorm 2019.3.3 warns me I have a duplicated jQuery selector

How can I fix this warning about the duplication? Is there any better way to do this process for the interaction on the database and front end forms? Also are there any additional improvements that I could add to this work to make it flow better?
$(document).ready(function() {
function authenticate(mode) {
if (mode === "Login") {
let User_email = $("input#log_User_email").val();
let Password = $("input#log_Password").val();
let error_collector = "";
let $log_response = $("div.box_response p#log_response");
$log_response.html("");
if (User_email.length <= 0)
error_collector += "Please enter a user email.";
if (Password.length <= 0)
error_collector += "Please enter a user password.";
if (error_collector !== "") {
$log_response.html(error_collector);
} else {
$log_response.html("Logging in");
$.ajax({
method: "POST",
url: "Resources/PHP/Processes/UserLogin.php",
data: {
User_email: User_email,
Password: Password
},
success: function(response) {
if (response === "Success") {
window.location = "details.php";
} else {
$log_response.html(response);
$("input#log_Password").val("");
}
}
});
}
}
How can fix this warning error for the duplication
Hopefully PHPstorm told you which one! In this case the selector you've duplicated is $("input#log_Password")
let Password = $("input#log_Password").val();
...
$("input#log_Password").val("");
You can remove the duplication by saving the value of the selector in the first instance at the point you read the password value, then reusing it later when you want to set the value i.e.
const $Password = $("input#log_Password");
let Password = $Password.val();
...
$Password.val("");

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

AJAX cannot read echo data from PHP?

I've been testing my register, and to an extent the code works. But it seems to not be able to compare the text from the PHP script.
I tried using existing email AND username, existing email, existing username and two non-existing username and email. But all give me the echoed data + Fail (which is the end conditional statement in JQuery).
JQuery:
$( function ajaxRegCheck() {
$('#reg_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'save_register.php',
data: $(this).serialize(),
success: function(data)
{
if(data == "un_em_exists"){
alert(data+" Username and Email exists.");
} else if(data == "un_exists") {
alert(data+" Username exists.");
} else if(data == "em_exists") {
alert(data+" Email exists.");
} else if(data == "success"){
alert(data+" Created account.");
} else {
alert(data+ " Fail.");
}
}
});
});
});
PHP Register:
if(($exist_check_user->rowCount() > 0) AND ($exist_check_em->rowCount() > 0)){
echo "un_em_exists";
} else if($exist_check_user->rowCount() > 0) {
echo "un_exists";
} else if($exist_check_em->rowCount() > 0) {
echo "em_exists";
} else {
$sql = "INSERT INTO Users (username, email, password) VALUES (:r_un, :r_em, :r_pw)";
$q = $cdb->prepare($sql);
$q->execute(array(':r_un'=>$reg_username,':r_em'=>$reg_email,':r_pw'=>$reg_pw));
echo "success";
}
I do not why it skips the if statements in the JQuery and go straight to the last else condition. It clearly outputs the string from the PHP side correctly, but it doesn't seem to be able to compare the string?
For example, if I register with existing username and email, it'll echo 'un_em_exists' response. On the JQuery the alert matches this as it says, "un_em_exists Fail.", which is the last statement.
UPDATE:
Found the problem, but not too sure how to fix. I tested the string length, and in return I get string length 16 (testing from the JQuery side), and on PHP I get 12 - which is the correct amount for "un_em_exists".
I do not know what the extra 4 amounts come from though.
After success trim your data by using data.trim(), might be there is whitespace
Make sure the returned value is text like so:
$( function ajaxRegCheck() {
$('#reg_form').submit(function(e) {
e.preventDefault();
$.ajax({
dataType: 'text',
type: "POST",
url: 'save_register.php',
data: $(this).serialize(),
success: function(data)
{
if(data == "un_em_exists"){
alert(data+" Username and Email exists.");
} else if(data == "un_exists") {
alert(data+" Username exists.");
} else if(data == "em_exists") {
alert(data+" Email exists.");
} else if(data == "success"){
alert(data+" Created account.");
} else {
alert(data+ " Fail.");
}
}
});
});
});

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

I need help on js and jquery form validation

i have problem with this query when i fill my email box with correct email it can validate and then ask me correct email and when i change my email box to empty it shows me correct email address. let check this http://www.icodecrew.com/register
if(email == "") {
$("span.val_email").html("Please Enter Your Correct Email-ID.").addClass('validate');
validation_holder = 1;
} else {
if(!email_regex.test(email)){ // if invalid email
$("span.val_email").html("Invalid Email!").addClass('validate');
validation_holder = 1;
} else {
$("span.val_email").html("");
$(document).ready(function(){
$("#email").change(function(){
$("span.val_email").html("<img src='spinner.gif' /> Please wait until we check...");
var email=$("#email").val();
$.ajax({
type:"POST",
url:"includes/checkemail.php",
data:"email="+email,
success:function(data){
if(data==0){
$("span.val_email").html("<img src='accept.png' title='available' />");
}
else{
$("span.val_email").html("<img src='error.png' /> E-Mail is Already registered");
}
}
});
});
});
}
}
As mentioned by #PlantTheldea in the comments to your question, your order of operations is severely broken. Having read through your code, this is the closest I can come to what I believe you want. It is UNTESTED and serves only to help you determine the order in which your steps should be executed:
$(function () {
var email_input = $('#email');
email_input.change(function () {
var status_display = $('span.val_email'),
email = email_input.val();
if (email === '') {
status_display
.html('Please Enter Your Correct Email-ID.')
.addClass('validate');
validation_holder = 1;
} else {
if (!email_regex.test(email)) {
status_display
.html('Invalid Email!')
.addClass('validate');
validation_holder = 1;
} else {
status_display
.html('<img src="spinner.gif" /> Please wait until we check...')
.removeClass('validate');
$.ajax({
type: 'POST',
url: 'includes/checkemail.php',
data: {
email: email
},
success: function (data) {
if (data == 0){
status_display.html('<img src="accept.png" title="available" />');
} else {
status_display.html('<img src="error.png" /> E-Mail is Already registered');
}
}
});
}
}
});
});

Categories

Resources