Problems with javascript validation in PHP document - php

I have this .php document where you can register on a webshop. I want to add javascript validation to it, but the site is made of .php completely, so no html head and body tags. Normally you can put the javascript source in the head tag, but in the .php you can't. (or at least i don't know how)
When testing the code, the javascript document seems fine, but when i put it in the .php document it gives certain errors about (") and ('). When i try to link to the seperate javascript document, the code doesn't seem to work at all.
(i've added the whole php page) Php document begin:
<?php
include 'header.php';
include 'menu.php';
echo '
function checkEmail(myForm)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(registration.emailAddress.value))
{
return (true)
}
alert("Invalid E-mail Address! Please re-enter.")
return (false)
}
function validatePwd()
{
var invalid = " "; // Spatie mag niet
var minLength = 6; // Minimaal 6 tekens
var pw1 = document.registration.password.value;
var pw2 = document.registration.passwordConfirm.value;
// Beide velden gelijke waarde
if (pw1 == "" || pw2 == "")
{
alert("Please enter your password twice.");
return false;
}
// Minimale lengte variabele
if (document.registration.password.value.length < minLength)
{
alert("Your password must be at least " + minLength + " characters long. Try again.");
return false;
}
// spatiegebruik variabele
if (document.registration.password.value.indexOf(invalid) > -1);
{
alert("Spaces are not allowed.");
return false;
}
else
{
if (pw1 != pw2)
{
alert ("You did not enter the same new password twice. Please re-enter your password.");
return false;
}
else
{
return true;
}
}
}
<div id="main">
<form name="registration" action="registerconfirm.php" method="post" id="form" onSubmit="return validatePwd()">
<h2>Personal Information</h2>
<fieldset class="login_register">
<label for="firstName" class="form">First name:</label>
<div class="registrationForm" id= "firstNameCheck"></div>
<input type="text" name="firstname" id="register_first_name"/>
<label for="lastName" class="form">Last name:</label>
<div class="registrationForm" id="lastNameCheck"></div>
<input type="text" name="lastname" id="register_last_name"/>
<label for="email" class="form">E-mail:</label>
<div class="registrationForm" id="emailCheck"></div>
<input type="text" name="emailAddress" id="register_email"/>
</fieldset>
<h2>Login Information</h2>
<fieldset class="login_register">
<label for="password" class="form">Password:</label>
<div class="registrationForm" id="lastNameCheck"></div>
<input type="password" name="password" id="password"/>
<label for="passwordCheck" class="form">Confirm password:</label>
<div class="registrationFormAlert" id="divPassCheck"></div>
<input type="password" name="passwordConfirm" id="passwordConfirm"/>
<input type="submit" class="button" value="SUBMIT"/>
</fieldset>
</form>
</div>
';
include 'footer.php';
?>
and the Javascript code:
<SCRIPT LANGUAGE="JavaScript">
function checkEmail(myForm)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(registration.emailAddress.value))
{
return (true)
}
alert("Invalid E-mail Address! Please re-enter.")
return (false)
}
function validatePwd()
{
var invalid = " "; // Invalid character is a space
var minLength = 6; // Minimum length
var pw1 = document.myForm.password.value;
var pw2 = document.myForm.passwordConfirm.value;
// check for a value in both fields.
if (pw1 == '' || pw2 == '')
{
alert('Please enter your password twice.');
return false;
}
// check for minimum length
if (document.myForm.password.value.length < minLength)
{
alert('Your password must be at least ' + minLength + ' characters long. Try again.');
return false;
}
// check for spaces
if (document.myForm.password.value.indexOf(invalid) > -1)
{
alert("Sorry, spaces are not allowed.");
return false;
}
else
{
if (pw1 != pw2)
{
alert ("You did not enter the same new password twice. Please re-enter your password.");
return false;
}
else
{
return true;
}
}
}

A couple of things: you can add a <script> tag anywhere you like. The attribute language, though, doesn't really exist, but that's not that important. All the same, it should be <script type="text/javascript">.
If your site is the output of (a bunch of) PHP scripts, why not simply echo the script?
echo '<script type="text/javascript" src="path/to/script.js"></script>';
Or, in the header file:
echo '<title>Title</title>';
?>
<script type='text/javascript'>
var script ='just add it here';
</script>
<?php
echo '</head>';//continue php
There's nothing preventing you to do this, either.

JavaScript is executed in the client's browser (aka, client-side), PHP is a server-side language.
Unless you plan on writing a JS interpreter for PHP, you can't run JS from PHP.
A better option would be to re-write the JS in PHP.
Unless you're having trouble including the file, then you'll just have to edit a:
<script type="text/javascript" src="myJSFile.js"></script> tag into your header.php.
So:
echo '<script type="text/javascript" src="myJSFile.js"></script>';

Try using PHPs HEREDOC Syntax to output the function.
http://www.php.net/manual/it/language.types.string.php#language.types.string.syntax.heredoc

Related

PHP MySQL mandatory field

I have this query
$tww_update_sql = "UPDATE `telesales_anc` SET
`Ime` = '".$_POST['Ime'];
and I have a form with submit button as follows:
<form id="contact" method="post" action="ANC_pozivanje_test.php">
<div class="col-md-2 col-sm-12 col-xs-12 form-group">
<small>Ime</small>
<input id="contact_name" type="text" name="Ime" placeholder="Ime" class="form-control" value="<?php echo $values['Ime']?>">
</div>
<div class="form-group">
<div id="contact_submit" class="col-md-9 col-sm-9 col-xs-12">
<button type="submit" class="btn btn-success" value="Save">Save</button>
</div>
</div>
Script that I used for checking in field is populated is as follows:
<script>
$(document).ready(function() {
<!-- Real-time Validation -->
<!--Name can't be blank-->
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!-- After Form Submitted Validation-->
$("#contact_submit button").click(function(event){
var form_data=$("#contact_name").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_name"+form_data[input]['']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free){
event.preventDefault();
}
else{
alert('Status nije popunjen');
}
});
});
</script>
Problem is when button is submitted (if field is not populated) I got message "Status nije popunjen" but form is submited regard message.
Is it necessary to use script for this?
It seems you check whether error_free is false, in which case you prevent for submission, however, if it is true (so if the field is populated), you only give an alert. Shouldn't event.preventDefault() be inside else?
You should not listen to button.click, but to form.submit.
<!-- After Form Submitted Validation-->
$("#contact").on('submit', function(event) {
The method event.preventDefault() will prevent the form from submitting, and should be in the same block as the alert()
if (!error_free) {
event.preventDefault();
alert('Status nije popunjen');
}
all you want to do is to validate the data on the client side, making sure that a valid name is supplied. i will recreate this here.
You can simply make changes to it. but i believe this solves your need. Also note that you should validate data on the server. dont just rely on client side validation
$update_sql = "UPDATE " . $table_name . " SET Ime = '" . $_POST['txt-name'] . "'";
'use strict';
$(document).ready(function() {
//bind click event on the button
var form = document.forms['frm-contact'];
$('#btn-contact').bind('click', function(event) {
event.preventDefault(); //this will prevent the form from getting submitted, so that we can validate the user name.
var field = form.elements['txt-name'],
name = field.value,
len = name.length,
error = '';
if (len === 0) {
error = 'Enter your name';
}
else if (len < 2) {
error = 'name should not be less than 2 characters';
}
else if (len > 36) {
error = 'name should not exceed 36 characters';
}
else if (/^[^a-z]+/i.test(name)) {
error = 'name must start with letters';
}
else if (!/^['.a-z\- ]+$/i.test(name)) {
error = 'invalid characters found'; // name should contain only alphabets, dash character, space character and dot character only
}
//done validating. show error now or submit the form.
if (error) {
alert(error);
$(field).addClass('error');
}
else {
$(field).removeClass('error');
form.submit();
}
});
});
.error {
background-color: red;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm-contact" id="frm-contact" method="post" action="example.php">
<div class="form-group">
<label for="txt-name">Name:</label>
<input type="text" name="txt-name" id="txt-name" placeholder="enter your name" value="" />
</div>
<div class="text-center">
<button type="submit" class="btn btn-success" name="btn-contact" id="btn-contact" value="contact us">SEND</button>
</div>
</form>

PHP AJAX form submit no page refresh multiple variable passing

fairly new to the language, i have created a simple login system and i am attempting to submit the forms without page refreshes. I have completely created the registration system without page refresh ( coupled with dynamic username checking) and am now attempting to convert the actual login form as well, so that the user can be displayed as logged in without page refresh.
I attempted to use the same method, however now i need to pass both username and password to the validation script, and i am unable to get the password part to work for some reason... although username works fine.
I have it set up to display one error if the password is validated successfully and the other if it is not.. i may be overthinking it, i appreciate your assistance in this possibly trivial problem
PS first go with stack so please point out any suggestions to formatting etc
PHP
<?php
require_once('startsession.php');
$page_title = 'Log In';
require_once('header.php');
require_once('connectvars.php');
require_once('navmenu.php');
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="invisiblelogin.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.error').hide();
$('#Info').hide();
});
function check_login(){
var username = $("#username").val();
var password = $("#password").val();
if(username.length > 0 && password.length > 0){
$.post("logincheck.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
//showing of errors is just visually showing me whether or not the password validation worked
$('#'+id).html(unescape(response));
var valid = $("#Info").html();
if( valid > 0) {
$("label#username_error2").show();
}
else {
$("label#password_error").show();
}
}
</script>
<div id="contact_form">
<form action="" name="contact">
<fieldset><legend>Log In Info</legend>
<font color="red"><div id="Info"></div></font>
<table>
<tr><td><label for="username" id="username_label">Username:</label>
<input type="text" id="username" name="username" value="" class="text-input" /></td>
<td><label class="error" for="username" id="username_error2">Enter your username. </label></td></tr>
<tr><td><label for="password" id="password_label">Password:</label>
<input type="password" id="password" name="password" value="" class="text-input" /> </td>
<td><label class="error" for="password" id="password_error">Enter your password. </label></td></tr></table>
<input type="submit" name="submit" class="button" id="submit_btn" value="Sign Up" onclick="return check_login();" />
</fieldset>
</form>
</div>
<?php
// Insert the page footer
require_once('footer.php');
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var username = $("input#username").val();
var password = $("input#password").val();
if (username == "" || password == "") {
if (username == "") {
$("label#username_error2").show();
$("input#username").focus();
}
if (password == "") {
$("label#password_error").show();
$("input#password").focus();
}
return false;
}
return false;
});
});
Intermediate PHP
<?php
require_once('connectvars.php');
if($_REQUEST)
{
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die (mysqli_error());
$username = mysqli_real_escape_string($dbc, trim($_REQUEST['username']));
$password = mysqli_real_escape_string($dbc, trim($_REQUEST['password']));
$query = "SELECT * FROM login_info WHERE username = 'username' AND password = SHA('$password')";
// ------------ THIS PASSWORD PART DOES NOT READ CORRECTLY
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) > 0) {
echo '1';
}
else {
echo '0';
}
}
?>
Ok.. a Few things...
I think you need to troubleshoot the 2 things it could really be... 1) Is the correct value being passed through to the PHP Page? You can check this in the CONSOLE of firebug (an extension for firefox that every developer should have). 2) Is your actual password validation working OK? Hard-code the password. Use the die() function to output data in the PHP page. The result will be seen in firebug as well.
If you're using $.post() on the JS side, your PHP should use $_POST instead of $_REQUEST. Shouldn't impact anything notable, but just thought I would add that.
This code is a little worrying...
if( valid > 0) {
$("label#username_error2").show();
}else {
$("label#password_error").show();
}
Most likely, valid is a string, and will not parse '0' as 0. While a login script is a true/false (0/1) procedure, PHP pages that are called by an ajax function should always return some sort of structure. For example...
Change your POST to expect a json response.
$.post("logincheck.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
setTimeout(function(){ //Note the change here.
finishAjax('Info', response); //Note the change here.
}, 450); //Note the change here.
}, 'json'); //Note the change here.
Then create a PHP function that will return a json package that your JS will use.
function SendJSONResponse($success, $msg=null, $additionalReturnData=null){
$result = array('success'=>$success);
if ($msg) $result['msg']=$msg;
if ($additionalReturnData) $result=array_merge($reult, $additionalReturnData);
die(json_encode($result));
}
Once you have that, your login script should look more like
if (mysqli_num_rows($data) > 0) {
SendJSONResponse(
true,
null,
array('data'=>$data) //Pass the logged in users info for use in JS
);
}else {
SendJSONResponse(false, 'Username or Password not found');
}
and your JS would look like this...
function finishAjax(id, response){
if( response.success) {
alert('logged in as ' + response.data.full_name + ' (' + response.data.email + ')');
$("label#username_error2").show();
}else {
alert(response.msg);
$("label#password_error").show();
}
}

PHP/JavaScript form validation?

I'm new with PHP and JavaScript. I eant to validate form, and if the form input fields are correct, then send it to php external script. I've tried something like this:
<head>
<script type="text/javascript">
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
} else if(y==null || y=="") {
alert("Input surname!");
} else if(z==null || z=="") {
alert("Input age!");
} else {
// IS IT POSSIBLE TO SEND FORM HERE FORM VARIABLES TO PHP SCRIPT?
}
}
</script>
</head>
<body>
<form name="forma" action="validate.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
Since you are not returning false from your function, the form should be being submitted anyway. You can stop it from being submitted by having your validate() function return false.
Your code looks correct, other than the fact you probably want to return false on failure to prevent the form from submitting. When not returning false, the form will simply continue to submit.
I also think you probably meant to name your form form not forma
You should validate the input server-side (php), even if you did it client-side (javascript).
You do this by checking on $_POST in validate.php:
Quite at the beginning of your script:
if (isset($_POST)) { // form has been sent
if (!isset($_POST['firstname']) || strlen($_POST['firstname'])==0) { // no entry
$e['firstname']='please enter a firstname!'; // prepare error-msg
}
if (!isset($e)) { // no error, continue handling the data
// write data to database etc.
}
}
// in your form...
if (isset($e)) echo "there were errors: ". implode(',',$e);
You need to put this code:
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
return false;
} else if(y==null || y=="") {
alert("Input surname!");
return false;
} else if(z==null || z=="") {
alert("Input age!");
return false;
} else {
return true;
}
}

Check User Validation in MySql with javascript

i want check in my mysql database if the user enter the username and password correctly and then go in the home.html, i have some javascript code that detect when the user click the login button, but i can't understand how check in the database with javascript, i know how do that in php, but i can't understand how call the php from the javascript or do it directly in the js code, this is some code:
the form in the html:
<div id="password">
<div class="input username"><input type="text" placeholder="User name" /></div>
<div class="input password"><input type="password" placeholder="Password" /></div>
<button>Log in</button>
Back
</div>
</div>
then in my Login.js file i have this:
function forgot() {
//Se ho scritto la password allora fai l'animazione wobble, altrimenti vai in home.html
if($("#password .input.password input").attr("value")!='') {
$.notification(
{
title: "Wrong password",
content: "Just leave the password field empty to log in.",
icon: "!"
}
);
$("#password").removeClass().addClass("animated wobble").delay(1000).queue(function(){
$(this).removeClass();
$(this).clearQueue();
});
$("#password .input.password input").attr("value", "").focus();
} else {
document.location.href = "home.html";
}
}
now for the login i detect only if the field are empty, but i want detect mysql database how i can check it? because i want if the user enter wrong username and password span a $notification alert, anyone can help me?
Please suppose your html form is like below:
<input id="uname" name="uname" type="text" placeholder="User name" />
<input id="pass" name="pass" type="password" placeholder="Password" />
<button id="btn_login">Log in</button>
And suppose php script named checkPassword.php is like below:
<?php
/*
1.Retrieve post data : "uname" and "pass".
2.Cehck if user name and password is valid.
*/
if( /* valid user name and password */ ){
echo "OK";
}else{
echo "NG";
}
?>
The Javascript code could goes like below:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(function() {
// set a event handler to the button
$("#btn_login").click(function() {
// retrieve form data
var uname = $("#uname").val();
var pass = $("#pass").val();
// send form data to the server side php script.
$.ajax({
type: "POST",
url: "checkPassword.php",
data: { uname:uname, pass:pass }
}).done(function( data ) {
// Now the output from PHP is set to 'data'.
// Check if the 'data' contains 'OK' or 'NG'
if (data.indexOf("OK") >= 0){
// you can do something here
alert("Login Successed.");
location.href = "ok.html";
}else if(data.indexOf("NG") >= 0){
// you can do something here
alert("Login Faild.");
location.href = "ng.html";
}
});
});
});
</script>
You can't communicate directly from client side JS to a server side database.
To make an HTTP request (to a server side program), use the XMLHttpRequest object.
if(document.pressed=='SUBMIT')
{
var uname = document.getElementById('uname').value;
if(uname.trim()=='' || uname.trim()==null)
{
alert("<?php echo 'uname_null'?>");
return false;
}
}
you can do the validation part on the sql server side if you use stored procedures

php include causing jquery submit function to not work

I'm trying to submit a form. The form is in html I'm using jquery to pass the form to a php page for processing and json_encode to pass back the results to display to the user. If I try to add an incude xxx.php on the php page that jquery is submitting to it kills the whole thing.
Here is how it lays out:
This is the main layout page and includes the form as you can see
<form id="jq_forgot_password" class="forgot_password" action="" method="post" name="password_form">
<?PHP include 'widgets/recover_pass.php'; ?>
</form>
This is the content of the form itself:
<!-- Password Recovery Form-->
<div class="form_text">
<p>
<label for="email">Email:</label>
<input type="email" id="recover_email" name="recover_email" placeholder="Enter your email address" class="field_boarder" value="" size="25px" maxlength="255"/> </p>
<div class="login_button_container">
<input name="login_button" type="submit" class="login_button" value="Submit"/>
</div>
</div>
This is the jquery script that is posting the form data and preventing the default submit button from refreshing the page:
// Forgot Password Validation and Post Function
$(function(){
$("#jq_forgot_password").submit(function(e){
e.preventDefault();
$.post("widgets/recover_pass_process.php", $("#jq_forgot_password").serialize(),
function(data){
if(data.email_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html("<div'> Sorry you must enter a valid e-mail address. Try again.</div>");
} else {
$('div.message_error').hide();
$('form#jq_forgot_password').hide();
$('div.message_success').fadeIn();
$('div.message_success').html("<div'>You're Password has been sent to" + data.email + ". Thank you </div>");
}
}, "json");
});
});
This is the php file that the jquery submit function is submitting to:
<?php
$email_check = '';
$return_arr = array();
if(filter_var($_POST['recover_email'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
$return_arr["email"] = $_POST['recover_email'];
echo json_encode($return_arr);
?>
This all works fine BUT if I add an include statement at the top of the recover_pass_process.php like this:
<?php
include 'func/user.func.php';
$email_check = '';
$return_arr = array();
if(filter_var($_POST['recover_email'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
$return_arr["email"] = $_POST['recover_email'];
echo json_encode($return_arr);
?>
Then it all comes to a screeching halt even if the included file has nothing in it. Just the fact that I'm trying to include another file kills it.
What am I doing wrong??? Thank you in advance!!
$("#jq_forgot_password").live("submit",function(e){
e.preventDefault();
$.post("widgets/recover_pass_process.php", $("#jq_forgot_password").serialize(),
function(data){
if(data.email_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html("<div'> Sorry you must enter a valid e-mail address. Try again.</div>");
} else {
$('div.message_error').hide();
$('form#jq_forgot_password').hide();
$('div.message_success').fadeIn();
$('div.message_success').html("<div'>You're Password has been sent to" + data.email + ". Thank you </div>");
}
}, "json");
});
try this..

Categories