Javascript not working after filename change - javascript

I created a simple registration (sign-up) form for my website.
The form includes a few validity checks (such as : making sure that the email is in the correct format; making sure that the username does not already exist in the database; etc, etc)
All these required JS, which I provided with the proper JS functions, and included a JS script with my files :
**<script src="jquery-1.11.2.js" type="text/javascript"></script>**
Everything was working perfectly..........until I changed the name of my registration file from "index.html" to "signup.php"
Now, it's all screwed up. The form still works. But, the JS functions and validity checks are dead! Nothing works.
There are no similar issues here on StackOverflow; however, I was able to find one issue on google. The poster suggested using a "Javascript Initialization" to solve the issue, but he did not provide an example of exactly how he did this.
Here is my JS code :
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 4;
//result texts
var characters_error = 'You must enter a minimum of 4 characters!';
var checking_html = 'Checking Username Availability....';
//when button is clicked
$('#login').keyup(function(){
//run the character number check
if($('#login').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
$('#email').keyup(function(){
//run the character number check
if($('#email').val().length > 0 ) {
//if it's bellow the minimum show characters_error text '
$('#email_availability_result').html(checking_email);
}
else{
//else show the cheking_text and run the function to check
$('#email_availability_result').html(checking_email);
check_email();
}
});
});
//function to check username AND email availability
function check_availability(){
//get the username
var login = $('#login').val();
var button_check=true;
//use ajax to run the check
$.post("check.php", { login: login },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
button_check=false;
document.getElementById("submit").disabled = false;
$('#username_availability_result').html(login + ' is
available.');
}else{
//show that the username is NOT available
button_check=true;
document.getElementById("submit").disabled = true;
$('#username_availability_result').html('Sorry, but [' + login +
'] is not available. Please choose another username.');
}
});
}
This script checks for "username availability" and also that the username has "a minimum of 4 characters" and also "email availability", etc, etc
(I did not enter the full code, as I assume it is not necessary). These are just examples of part of my code.
And here is the form (the input entry for username)
Choose a username :
UPDATE
I solved the issue of why the JS functions were not working : I had to specify the FULL PATH to the JS source-file, beginning with https://......etc.
However, something still remains unclear : the form displays the message "Checking Username Availability".........or "Checking Email Validity". But, if the username is available/unavailable, or email is valid/invalid.........it does not display these messages!
The "Checking Username Availability" message remains stuck on display :((

Answer found.
A simple, stupid mistake on my part (haha)
After changing the file name to "sign-up.php", I forgot to remove the PHP extension. So, naturally, my server did not know where to look for it

Related

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

Search in mysql by Javascript

Good morning , I'm trying to do a check if the cpf entered already exists in the database , I'm using laravel , someone could help me in this function please ?
In my controller I seek and I list all cpfs in bank :
$cpfduplicado = UsuarioEsic::lists('doc', 'id')->all();
foreach ($cpfduplicado as $cpf)
if ($cpf == $request->cpf)
$cpf = 'verdadeiro';
// return redirect('/Esic/CadastroFisica');
return redirect('/Esic/Sucesso');
I'm not sure how to make a function in javascript to get this data and set a custom browser validity , I did something like this:
$(function cpfdupli(input) {
$('.btnCadastroo').on('click', function (json){
if (json.cpf === 'verdadeiro'){
document.getElementById('cpff');
input.setCustomValidity('Cpf já existe.');
} else {
input.setCustomValidity('');
}
});
});
I am beginner in the field and do not really know how to do this work, I just wanted the cpf existed already setasse one CustomValidity in the browser and not let him continue with the registration , if anyone can help me or give me other ways of how solve this I would be very grateful!
PS: Any questions about the code will be available to provide.
ok i will attempt to try and do what your looking for:
Say the html input is something like:
<input type="text" value="" id="cpff" />
Then we have some js to get the details within the above input box, the below does this on each lette typed into the input so its constantly checking as the user types then giving a visual reposnse as the user types so they now if its taken or not as typing:
$('input#cpff').on('keyup', function(evt){
//-- get for value on keyup
var inputValue = this.value;
//-- call to the controller to check
$.ajax({
url : '/check/cpff/',
type: 'POST',
data {cpffValue : inputValue},
success : function(res){
console.log(res);
if(res === 'succcess'){
//-- output a tick icon to let the user know all is ok so far
} else {
//-- output an red x to sai no its been used
}
},
error : function(msg, x){
console.log(msg);
}
})
});
So for each letter typed in the input box the code sends the value to the route /check/cpff and then this returns a boolean / string back to see if its ok or not, hopefully your still with me?
Route:
Route::post('/check/cpff', ['uses' => 'ControllerName#checkCPFF']);
Controller
Class ControllerName extends Controller {
public function checkCPFF(Request $request){
//-- get the ajax data variable -- cpffValue
$formValue = $request->get('cpffValue');
//-- lets chec to see if we have an entry with those values
$doesItExsist = ModelName::where('field_name',$formValue);
//-- if we have a result from the DB then return not allowed
return ($doesItExsist) ? 'not-allowed' : 'allowed'
}
}
SO the above controller takes the data value that the form submits, then checks the required db table and does a search for that value, if it cannot then the user has a valid entry if there is a value found then the user must change their entry etc
its a bit crude and i have nothing to test this with etc so might / will need better working / writing to work as such, you can always change the js to do the same on submitting the form instead etc,
here is a link to test out the input section. to veiw the result open the console up so you can see the values being typed. Example of keyup
i hope it gives your a sort of starting base for help...

What is wrong with my code (in Javascript)?

I'am really frustrated with the result I'm getting in my code:
userOldPass //from user input, user's old password
oldPass //from database, user's old password
newPass //from user input, user's new password
confirmNewPass //from user input, user's new password confirmation
function checkpass(){
if(userOldPass==oldPass) && (newPass==comfirmNewPass){
alert('success');
}else{
alert('error');
}
}
The problem is it always says 'error' even if the inputs are already all correct. I checked each variables' values via the alert function to see if there is some inequalities but everything is okay and still it alerts 'error'.
What could be the problem?
P.S. all the variables are in SHA1 hash. I used the CryptoJS.SHA1 function I found in the net.
I use the alert function to check each value from the variables and the results are right.
if(userOldPass==oldPass) && (newPass==comfirmNewPass) // all should stay in ()
In this way:
if ((userOldPass==oldPass) && (newPass==comfirmNewPass))

Validating more that one email field

Im using Joren Rapini's validation code to for my online form. Joren's Website
It allows you to check to see if an email address has been correctly entered, but I have 2 email addresses that I want to validate in the form.
Any idea how I would do this?
I've tried adding in email = $("#youremail"); as well as the one that's currently in the code which is email = $("#receiveremail"); but it only works for one.
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["youremail", "name", "receiveremail", "message"];
// If using an ID other than #email or #error then replace it here
email = $("#receiveremail");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field";
emailerror = "Not a vaild email";
});
He doesn't do a great job of explaining this, but it's fairly straightforward. You have to validate two separate email fields:
if (!/^S+#S+.S+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
var email2 = $("#youremail");
if (!/^S+#S+.S+$/.test(email2.val()) {
Of course it would be better to loop over the emails in a similar setup to how required is done.
Use var too.
You need to run the validation code for your other field
in document.ready
otheremail = $("#otheremail");
in form submit
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(otheremail .val())) {
otheremail .addClass("needsfilled");
otheremail .val(emailerror);
}
No offense to Joren Rapini but this code is hacky and shouldn't be used for other than the smallest purpose.

Categories

Resources