return true for same page validation - php

I am having trouble with a same page AJAX/JavaScript/PHP Captcha validation code. The original code is from http://www.phpcaptcha.org. We are using a third party site to store all of our form data into a database that is edited by multiple people. Lately we've been receiving a ton of spam so we're trying to implement this Captcha.
I'll cut to the chase here. The code is set to 'return false' every time. I need it to 'return true' if certain conditions are met. The code is as follows:
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
if( isset($_POST['captcha_code']))
{
$a = array("error"=>0);
print json_encode($a);
}
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript">
//variables not part of original code
function reloadCaptcha()
{
//original code ElementId labled 'captcha_code'
document.getElementById('captcha').src ='securimage_show.php?sid=' + Math.random();
}
var r, Submit;
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('zoho1').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return Submit;
}
}
</script>
The process_si-zoho1() is as follows:
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != '-------') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$captcha = $_POST['captcha_code']; // the user's entry for the captcha code
$errors = array(); // initialize empty error array
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
//Edited out mail function from original code
//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
$Submit = true;
$entry = array('error' => 0, 'submit' => $Submit);
die(json_encode($entry));
} else {
$errmsg = $captcha_error;
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
$Submit = false;
}
//Added $Submit to the return array
$return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
die(json_encode($return));
}
} // POST
} // function process_si_zoho1()
?>
The 'processForm()' runs when the submit button is clicked. I'm sure i'm missing something really simple here, I'm just too involved in it. I really appreciate your help
I know that the value of 'Submit' is not defined until the PHP in the AJAX.Request() runs but I can't figure out how to define the variable from the start. FYI, the variables 'r' and 'Submit' are all declared outside the function itself so are global variables. If I try to insert a return into the try/catch it will always give me the error in the catch "There was an error parsing the json." Also, with the code as it is now, it will always give me the same error and submit the form anyways, as the value of Submit is blank. Even if I define the Global variable "Submit" as "false" it still returns as though it is blank.
If anything other than 'return false' is declared at the bottom of the function, it will submit the form without validating the Captcha. I'm very new to all this, but I've been researching for almost 2 weeks now for 4-8 hours a day and have yet to find a working code. Is it even possible? I mean, other websites use same page validation and submit to third party databases right?
I can provide more code if needed, but the problem seems to be here. If I don't try to change the return, the Captcha validates fine and the 'if (r.error == 0)' code executes fine. I have even added an alert to show the value of 'Submit' just to verify the data is transferring between the functions.
I'm at my wit's end here. I would appreciate any help.
Thanks,
Matt
The complete code (minus details) is as follows:
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript">
//variables not part of original code
function reloadCaptcha()
{
//original code ElementId labled 'captcha_code'
document.getElementById('captcha').src = '/securimage_show.php?sid=' + Math.random();
}
var r, Submit;
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('zoho1').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit;
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return false;
}
}
</script>
</head>
<body>
<form action="----------" id="zoho1" method="POST" name="leadForm" onsubmit="return processForm()">
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input type="hidden" name="do" value="contact" /><br />
<p>
<label for="First Name">First Name</label><br />
<input class="required" maxlength="40" name="First Name" type="text" /></p>
<p>
<label for="Last Name">Last Name</label><br />
<input class="required" maxlength="80" name="Last Name" type="text" /></p>
<p>
<label email="" for="">Email</label><br />
<input class="required validate-email" maxlength="100" name="Email" type="text" /></p>
<p>
<label for="Phone">Main Phone</label><br />
<input class="required" maxlength="30" name="Phone" type="text" /></p>
<p>
<label for="Mobile">Mobile Phone</label><br />
<input maxlength="30" name="Mobile" type="text" /></p>
<p>
<label for="State">State</label><br />
<select class="required validate-selection" name="State"><option selected="selected" value="-None-">-None-</option><option value="AL">AL</option><option value="AK">AK</option><option value="AZ">AZ</option><option value="AR">AR</option><option value="CA">CA</option><option value="CO">CO</option><option value="CT">CT</option><option value="DE">DE</option><option value="DC">DC</option><option value="FL">FL</option><option value="HI">HI</option><option value="ID">ID</option><option value="IL">IL</option><option value="IN">IN</option><option value="IA">IA</option><option value="KS">KS</option><option value="KY">KY</option><option value="LA">LA</option><option value="ME">ME</option><option value="MD">MD</option><option value="MA">MA</option><option value="MI">MI</option><option value="MN">MN</option><option value="MS">MS</option><option value="MO">MO</option><option value="MT">MT</option><option value="NE">NE</option><option value="NV">NV</option><option value="NH">NH</option><option value="NJ">NJ</option><option value="NM">NM</option><option value="NY">NY</option><option value="NC">NC</option><option value="ND">ND</option><option value="OH">OH</option><option value="OK">OK</option><option value="OR">OR</option><option value="PA">PA</option><option value="RI">RI</option><option value="SC">SC</option><option value="SD">SD</option><option value="TN">TN</option><option value="TX">TX</option><option value="UT">UT</option><option value="VT">VT</option><option value="VA">VA</option><option value="WA">WA</option><option value="WV">WV</option><option value="WI">WI</option><option value="WY">WY</option><option value="GA">GA</option></select></p>
<!--<div><label for="Mailing Zip">Mailing Zip</label><br /><input type="text" maxlength="30" name="Mailing Zip" /></div>--><!--<div><label for="Mailing Country">Mailing Country</label><br /><input type="text" maxlength="30" name="Mailing Country" /></div>-->
<p>
<label for="----------">----------</label><br />
<select class="required validate-selection" name="----------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
<p>
<label for="-------">----------</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
<p>
<label for="-------">------------</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="---------">-----------</option></select></p>
<p>
<label for="-------">Intended Degree</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="--------------">-------------</option><option value="-------------">-------------</option><option value="-------------">--------------</option></select></p>
<p>
<label for="-------">How did you hear about TTU?</label><br />
<textarea class="required" height="250" maxlength="1000" name="-------" width="250"></textarea></p>
<p>
<label for="Description">Comments</label><br />
<textarea height="250" maxlength="1000" name="Description" width="250"></textarea></p>
<img id="captcha" src="/securimage_show.php" alt="CAPTCHA IMAGE" />
<input type="text" id="enterVerify" name="captcha_code" size="10" maxlength="6" />
<input type="button" id="reload" name="Reload" value="Reload" onClick="reloadCaptcha()">
<input class="form-button" name="save" type="submit" value="Submit" />
</form>
</body>
</html>
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != '-------') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$captcha = $_POST['captcha_code']; // the user's entry for the captcha code
$errors = array(); // initialize empty error array
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
//Edited out mail function from original code
//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
$Submit = true;
$entry = array('error' => 0, 'submit' => $Submit);
die(json_encode($entry));
} else {
$errmsg = $captcha_error;
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
$Submit = false;
}
//Added $Submit to the return array
$return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
die(json_encode($return));
}
} // POST
} // function process_si_zoho1()
?>

<?php
if( isset( $_POST['captcha'] ))
{
$a = array("error"=>0);
print json_encode( $a );
exit();
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js" ></script>
</head>
<body onload="processForm()">
<form id="formtest" action="" method="POST">
<input type="text" name="captcha" value="1vfvrfr">
</form>
<script>
var r, Submit;
function reloadCaptcha(){}
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('formtest').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return Submit;
}
</script>
</body>
</html>

Thanks for all the help. I did some more research, the problem was in the JavaScript (my least experienced portion of code). I simply added to the:
if (r.error == 0)
document.forms['formname'].submit();
Thanks for the help guys! I'll definitely be using this forum again!

Related

Form submission in php

I have a little problem with my if(isset($_POST['submit'])) code. What I want is to run the processForm() function when the submit button for the form has been clicked. The problem is that when I include the if(isset($_POST['submit'])) function, when I click on the submit button the processFunction() does not run at all.but when i include if( !isset($_POST['submit'])) the processForm() function runs... Why is this and can you help me out with this issue please
<html>
<head>
<title>Membership Form</title>
<style type="text/css">
.error { background: #d33; color: white; padding: 0.2em; }
</style>
</head>
<body>
<?php
if ( isset($_POST["submit"])) { //if submit input has value
processForm();//calls the processForm function
}
function processForm(){
$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();
foreach ($compulsaryForm as $input) { //loop
if (!isset($_POST[$input])) {
$missingFields[] = $input;
} // forget the else part cause we mainly want to avoid the warning msg
}
if ($missingFields) {
echo "<p>there are missingFields</p>";
}
}
?>
<form action="htmlForms2.php" method="post">
*name:<input type="text" name="firstName"> <br><br>
*last name: <input type="text" name="lastName"> <br><br>
*password<input type="password" name="password"> <br><br>
*retype password<input type="password" name="passwordRetype"><br><br>
male:<input type="radio" name="sex"><br>
female:<input type="radio" name="sex"><br>
favourite food:<select name = "favourite">
<option value="select">select</option>
<option value="rice">rice</option>
<option value="beans">beans</option>
</select><br>
do you want to recieve news letter?<input type="checkbox" name="newsLetter"><br>
Any comments? :<input type="text" name="comments"><br>
<input type="reset" name="reset">
<input type="submit" name="submit" value="submit">
</form>
your code looks fine in terms of the "submit" field validation. What does not looks fine are these lines:
$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();
foreach ($compulsaryForm as $input) { //loop
if (!isset($_POST[$input])) {
...
All the inputs you're validating against will be sent in the submission, so isset(...) will be true, they may be empty but they will exist for sure. So validate your emptyness on the server side or before sending the form, or even better in both places and it should work ;)
// Use: count($_POST[$input]) < 5, In case you want to validate the text length
if ( !isset($_POST[$input]) || empty($_POST[$input]) || count($_POST[$input]) < 5 {

How do i clear this array by user input in php/html?

I am working on a program that has the user type in their course, first name, last name, and description of a program. The code is mostly done except for getting the clear the array button to work. When I use the unset array to clear the array on its own, it works but then the user cant enter in more data. I want to have the user be able to clear the data. Here is my code:
<?php
session_start();
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
<?php
function clear(){ //this is the problem
unset($_SESSION['courses']);
return true;
}
?>
</head>
<body>
<form method="POST">
Course: <input type="text" name="courses" />
<br /><br />
First Name: <input type="text" name="firstname" />
<br /><br />
Last Name: <input type="text" name="lastname" />
<br /><br />
Description: <input type="text" name="description" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
if (!isset($_SESSION['courses']))
$_SESSION['courses'] = array(); // Initialize the array if it doesn't exist
// Add the value to our array
$_SESSION['courses'][] = array("course" => $_POST['courses'],
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"description" => $_POST['description']);
}
// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
echo $course['course']." ".
$course['firstname']." ".
$course['lastname']." ".
$course['description']." ".
"<br />";
}
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()"> //this is the problem
<?php
?>
</body>
</html>
Can someone please help?
<?php
// there is nothing wrong with this function.
function clear() {
unset($_SESSION['courses']);
return true;
}
?>
Okay, this function is fine, there is nothing wrong with it. But, you can't use this function like:
<input type="submit" name="Clear" onclick="Clear()" /> <!-- this is the problem -->
You see that onclick="Clear()", and that php function clear()? Yeah, you can't execute php functions with a html onclick="". You can only do that with javascript functions.
But you can do something like this:
<?php
if(isset($_POST['Clear']))
{
// if the user submits the form, then the following code will be executed.
clear();
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()">
clear() would be calling a javascript function. You have correctly written a php function.
Check the value of the submit button "Clear" to be "clear" and if true run the PHP function clear().
if ($_POST['Clear'] === 'clear') {
clear();
}

javascript does not validate multiple forms in a single php page

i am new to web development.
I have a question about validating user input data in a single php page:
this is my code
<html>
<head>
<script lanauge="JavaScript" type="text/javascript">
function validate_skill_name()
{
if (document.worker.skill_name == null
|| document.worker.skill_name == "") {
alert("skill name field is incorrect");
document.worker.skill_name.focus();
return false;
}
return true;
}
function validate_skill_id()
{
if (document.worker.worker_id1 == null
|| isNaN(document.worker.worker_id1)) {
alert("skill: worker id 1 field is incorrect");
document.worker.worker_id1.focus();
return false;
}
return true;
}
function validate_time_id()
{
if (document.worker.worker_id2 == null
|| isNaN(document.worker.worker_id2)) {
alert("time: worker id 2 field is incorrect");
document.worker.worker_id2.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<h1> Select Workers </h1>
<form name="worker" action="" method="post" onsubmit="return(validate_skill_name());">
Skill Name: <input type="text" name="skill_name"/><br />
<input type="submit" value="submit me!"/>
</form>
<h1> Get Worker Skill </h1>
<form name="worker" action="" method="post" onsubmit="return(validate_skill_id());">
ID: <input type="text" name="worker_id1"/> <br />
<input type="submit" value="submit me!"/>
</form>
<h1> Get Worker Available Time </h1>
<form name="worker" action="" method="post" onsubmit="return(validate_time_id());">
ID: <input type="text" name="worker_id2"/> <br />
<input type="submit" value="submit me!"/>
</form>
<?php
require_once "../logic.php";
if ($_POST) {
$result = NULL;
if (array_key_exists('worker_id2', $_POST)) {
$result = logic_get_worker_available_time($_POST['worker_id2']);
} else if (array_key_exists('skill_name', $_POST)) {
$result = logic_select_has_skill($_POST['skill_name']);
} else if (array_key_exists('worker_id1', $_POST)) {
$result = logic_get_worker_skills($_POST['worker_id1']);
}
echo htmlspecialchars(print_r($result));
}
?>
</body>
my question is that, this code does not validate user input data. I do not know why. Because I did exactly same thing with my other php pages except they only have one form instead of mutiple forms like in case.
as a result, user input does not get validated. $_POST request always get sent to my logic.php.
Hope anyone can help me out.
You should use ID attributes to uniquely identify elements on the page - such as a form in your case.
<form id="myFormID">
<input name="skill_name" type="text" />
</form>
Then you can reference the form via javascript:
document.getElementById("myFormID");
function validate_skill_name()
{
var formElm = document.getElementById("myFormID");
if (formElm.skill_name.value == null || formElm.skill_name.value == "") {
alert("skill name field is incorrect");
formElm.skill_name.focus();
return false;
}
return true;
}
Furthermore, an even better way would be to use jQuery:
$("#myFormID").submit(function(){
var inputElmVal = $("input[name=input_field_name]").val();
if(inputElmVal == '')
{
// Do your null validation here ....
}
});
You need to use value, the name of the input is html element
function validate_skill_name() {
if (document.worker.skill_name.value == null
|| document.worker.skill_name.value == "") {
alert("skill name field is incorrect");
document.worker.skill_name.focus();
return false;
}
return true;
}
http://jsfiddle.net/gcREC/

multiple button with one onsubmit

I am having two buttons in a form ques and ans. When i click the ques button the same form with some text-fields will get open and in the form I've two buttons add and clear. By clicking add the entered field will be entered to the database. Like wise the same thing for clicking the answer button. I'm having one onsubmit=return valid() for both the buttons. I've to write separate script for both buttons, checking the conditions. But I'd written for only answer button. I dont know how to write for both buttons in one function valid(). Please tell me how to write for both buttons inside a function.
function valid()
{
var quest=document.getElementById('ques1').value;
var cno=document.getElementById('cno').value;
var pno=document.getElementById('pno').value;
quest1=trim(quest1);
pno=trim(pno);
cno=trim(cno);
if(quest=="")
{
alert("Please enter Question");
document.getElementById('ques1').focus();
return false;
}
else if( pno=="")
{
alert("Please enter valid Page No");
document.getElementById('pno').focus();
return false;
}
else if (cno=="")
{
alert("Please Select Chapter No");
document.getElementById('cno').focus();
return false;
}
}
You can do something like this
function validate(button_value) {
if(button_value=='test1') {
if(document.getElementById('rest1').value=="") {
alert('Blank for input 2');
return false;
}
} else if(button_value=='test') {
if(document.getElementById('rest').value=="") {
alert("Blank for input 1");
return false;
}
}
}
The HMTL I tested in:
<form method="POST" action="" onsubmit="return validate(this.submited);">
<input type="text" name="rest" id="rest" value=""/>
<input type="text" name="rest1" id="rest1" value=""/>
<input onclick="this.form.submited=this.value;" type="submit" id="test" value="test"/>
<input onclick="this.form.submited=this.value;" type="submit" id="test1" value="test1"/>
</form>
Hope this helps
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validate(this.submited);">
Question : <input type="text" name="ques">
Answer : <input type="text" name="ans">
<input type="submit" name="subques" value="Ask Question"/> <input type="submit" name="subans" value="Reply Answer"/>
</form>
<hr>
<?php
if(isset($_POST['subques']))
{
if(isset($_POST['ques']))
{
if($_POST['ques'] != '' && $_POST['ques'] != NULL)
{
echo "Your question is: " . $_POST['ques'];
}
}
}
if(isset($_POST['subans']))
{
if(isset($_POST['ans']))
{
if($_POST['ans'] != '' && $_POST['ans'] != NULL)
{
echo "Your answer is: " . $_POST['ans'];
}
}
}
?>

jQuery 'clone' script with other variables doesn't work

I have 'cloned' a script, except for the variables the script is exactly the same as the original! But it just doesn't entirely work. it get stuck at:
if(validConnection=="")
{
$('#UsernameConnection').css('border-color','#00ff00');
$('.ErrorUsernameConnection').text('');
checkUsername1 = true;
}
(the rest of the code is below)
I have been checking if I made some mistake in changing the varables but they all seem to match properly. What is wrong? How comes it work fine just with different variables and not this time???
Here is the HTML:
<div id="Connection">
<div class="Connection">
Connection
<strong>×</strong>
</div>
<?php connection(); ?>
<div class="formConnection">
<form method="POST" autocomplete="off" name="Connection">
<label for="Connection">Username:</label><br/>
<input type="text" name="UsernameConnection" id="UsernameConnection"/><br/>
<span class="ErrorUsernameConnection"></span><br/>
<label for="Connection">Password:</label><br/>
<input type="password" name="PasswordConnection" id="PasswordConnection"/>
<span class="ErrorPasswordConnection"></span><br/>
<input type="checkbox" name="checkbox"/><label>Remember me</label><br/>
<input type="submit" name="Connection" value="Log In" id="Connection" class="LogIn"/>
</form>
</div>
Here is the php:
<?php
if(isset($_POST['UsernameConnection']))
{
$Username1 = $_POST['UsernameConnection'];
if(preg_match("/^([a-zA-Z0-9àáâãäåçèéêëìíîïðòóôõöùúûüýÿ]{1,}[._-\s]?)+[a-zA-Z0-9àáâãäåçèéêëìíîïðòóôõöùúûüýÿ]{1,}$/",$Username1))
{
echo "";
}else
{
echo "Invalid";
}
}
?>
and JS:
$(document).ready(function(){
var checkUsername1 = false;
$('#UsernameConnection').keyup(function(){
var Username1 = $('#UsernameConnection').val();
if(Username1=="")
{
$('#UsernameConnection').css('border-color','red');
$('.ErrorUsernameConnection').text('Error message 1');
checkUsername1 = "Username empty";
}else
{
$.post('fonctions/validUsernameConnection.php',{Username1:Username1},function(validConnection)
{
$('.ErrorUsernameConnection').text(validConnection);
if(validConnection=="")
{
$('#UsernameConnection').css('border-color','#00ff00');
$('.ErrorUsernameConnection').text('');
checkUsername1 = true;
}else
{
$('#UsernameConnection').css('border-color','orange');
checkUsername1 = "Username Invalid";
}
});
}
});
});
PS: I'm a little bit lost with all the stack's sites so forgive me if this isn't the right one to post this =/
the problems seems to be with this line
$.post('fonctions/validUsernameConnection.php',{Username1:Username1},
function(validConnection)
In your PHP you should check for $_POST['Username1'] instead of $_POST['UsernameConnection']

Categories