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

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']

Related

Refresh page after alert box using AJAX in php

I'm doing a form validation in my php script, take one column as an example, if the username is not filled, an alert window will pop up and say "please enter your username", after user click "ok", the whole page refresh but the information on the form will be reset too.
So I would like to keep what the user has input after refreshing the page, how can I embed the code in php using AJAX?
//username validation
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
the website is in php file, html code is embedded under the php stuff, and this is the form in the html
<div id="account">
<form method="POST">
<p><span class="error">* required field.</span></p>
Username:
<input type="text" name="Username">
<span class="error">* </span><br>
<!--other fields..-->
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="signup_button">
</form>
</div>
<?php
if(isset($_POST['signup_button'])){
$Username = $_POST['Username'];
}
?>
or...
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
/* save the value in the browser */
echo 'window.'+VarYouWantToKeep = $_POST['VarYouWantToKeep'];
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
( or use localStorage, instead of window. https://developer.mozilla.org/en/docs/Web/API/Window/localStorage )
Then, when the page loads, check if('window.'+VarYouWantToKeep)
and if it's there, set it as the value="" of the corresponding form field
try this (This is taking into account you set $username to $_POST["Username"];)
<input type="text" name="Username" value="<?php if(isset($_POST["signup_button"]) && $_POST["signup_button"]=="Submit") {echo $username; ?>"
To store variable data, you will need to use $_SESSION variables in PHP. Make sure that session_start() is at the top of the PHP page.
Here's a basic example:
//this PHP page contains the HTML form
<form>
<input type="text" value="<?php echo $_SESSION['email']; ?>" />
</form>
//ajax
$.ajax({
url:'validate.php',
type:'POST',
data:{name:inputName}
}).done(function(data){
alert(data);
});
//php page
session_start();
if(!isset($_POST['name'])){
//set session variable
$_SESSION['email'] = $_POST['email'];
//this will be sent back to PHP page with HTML
echo 'Please enter username';
}
I coded here, a super cool login page with bootstrap as you expect. Link bootstarp cdn in your html file. This will show the error under the button instead of showing a windows classic alert box. I included ajax request and php response also with some validation.
login.html
<div class="container">
<div class="col-lg-offset-8 col-md-offset-6 col-lg-4 col-md-4 login-bg">
<form class="form-horizontal" role="form" action="#" method="">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="username" type="text" class="form-control" name="username" value="" placeholder="User Name" required tabindex="1" autocomplete="off">
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<input id="password" type="password" class="form-control" name="password" value="" placeholder="Password" required tabindex="2" autocomplete="off">
</div>
<br>
<div class="form-group">
<div class="col-lg-6">
<button class="btn btn-primary-outline btn-block" type="submit" id="login">Login</button>
</div>
<div class="col-lg-6">
<button class="btn btn-success-outline btn-block" type="reset">Clear</button>
</div>
</div>
<br>
<div id="login-feedback" class="btn-block"></div>
</form>
</div>
</div>
myStyle.js
<script type="text/javascript">
$(document).ready(function()
{
$('#login').click(function()
{
var uname=$('#username').val();
var pword=$('#password').val();
if(uname!='' && pword!='')
{
$('#login-feedback').text('validating....');
$.post("login-check.php",{username:uname,password:pword},function(data)
{
if(data=="success")
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','green').fadeTo(1000,1,function()
{
document.location='index.php';
});
});
}
else
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','red').fadeTo(900,1);
//reset form
$('#login').trigger("reset");
});
}
});
return false;
}
else
{
$('#login-feedback').text("Please enter all fields").css('color','purple');
}
});
});
</script>
login-check.php
<?php
//include connextion file;
if(!isset($_SESSION))
session_start();
$username=trim($_POST['username']);
$password=$_POST['password'];
$username=mysqli_real_escape_string($con,$username);
$password=mysqli_real_escape_string($con,md5($password));
if(($username) && ($password))
{
$query = mysqli_query($con,"select * from login where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows>= 1)
{
$fetch_result = mysqli_fetch_array($query);
session_regenerate_id(true);
$_SESSION['username']=$fetch_result['username'];
$_SESSION['status']=$fetch_result['status'];
// Close session variable assigns
session_write_close();
echo "success";
}
else
{
echo 'Login failed';
}
mysqli_close($con);
}
?>

return true for same page validation

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!

PHP returns loads of blank spaces

i have a login script that uses AJAX, but i have a problem with the code that i cannot work out.
Here is the code:
JS:
$(document).ready(function(){
$("#loginForm").submit(function(){
$("#report").removeClass().addClass('loader').html('Loading...').fadeIn(1000);
$.post("check_login.php",{ username:$('#signin_username').val(),password:$('#signin_pwd').val()},function(data){
console.log(data);
if(data == "TRUE"){
document.write(data);
console.log("YEP");
$("#report").fadeTo(200,1,function(){
$(this).html('Logging in.....').addClass('log').fadeTo(900,1,function(){
document.location='members/index.php';
});
});
}
else if(data == "FALSE"){
console.log("NOPE")
$("#report").fadeTo(200,1,function(){
$(this).html('Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
FORM:
<div id="login_form">
<h3>Login</h3>
<div id="signup_link">
Signup Now
</div>
<div id="report"></div>
<form action="" method="post" id="loginForm">
<ul>
<li>
<label for="username">Email: </label>
<input type="text" id="signin_username" name="signin_username" required="required" />
</li>
<li>
<label for="pwd">Password: </label>
<input type="password" id ="signin_pwd" name="signin_pwd" required="required" />
</li>
<li>
<input type="submit" name="login" id="login" value="Login"/>
</li>
<li>Forgot Password</li>
</ul>
</form>
</div>
and PHP file called by js:
require_once 'members/classes/Membership.php';
# Make instance of membership class
$membership = new Membership();
$true = "FALSE";
$false = "FALSE";
if(!empty($_POST))
{
$username = $_POST['username'];
$pwd = $_POST['password'];
if($test = $membership->validate_user($username, $pwd))
echo $true;
else
echo $false;
}
else
{
echo "Details werent entered";
}
Basically the method the php script is calling checks the database to see if the users details match and if they're allowed to login, if so returns true if not returns false (These are the only two values it will return.
So it works file until we get back into the js code, note the first "console.log" the output of this seems to have loads of white space before the word that im looking for something like this:
"
TRUE"
The space above the true is nothing so when i test if(data == "TRUE") it's never true.
Either something strange is happening or i'm missing something really silly. Can anyone see whats wrong?
Thanks for the time.
Make sure you haven't got any include files that are outputting whitespace. It's easy to make that mistake.

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/

Duplicated entries to mySQL using jQuery ajax and PHP

I am using jQuery (version 1.8.1) with PHP (version 5.3) to submit a form adding an entry into a mySQL database, what is happening is on the first submit everything is fine but for each subsequent submission without a page refresh it adds an additional entry.
In addition I'm also using Bootstrap (version 2.1.1) and the upload widget from Jasny for Bootstrap (version j1a) in the UI. I have not yet connected the upload widget to the processing or submit as I detected the duplication problem when I was implementing it.
Please note that this is a proof of concept system so the code is rough as I'm not going to invest in cleaning it up until the project is confirmed. Due to this, you will notice some inline mySQL queries, I know that this isn't the best way to do it however it works for the purpose of demonstration and will be cleaned up later. Also as a POC system it is on an internal server currently, I can share the code but cannot show an example site at this time unfortunately.
Now back to the issue, as an example, the first post for "Company 1" has 1 record added for "Company 1", the second record for "Company 2" adds 2 records for "Company 2", the third record for "Company 3" adds 3 records for "Company 3" and so on. If I reload the form page in any way (refresh or a new request) the problem restarts from the first submission.
I am using jQuery serialize with ajax to post the data to the PHP processor. I have logged all of the posts being received by the processor and I see the processor is receiving multiple records from the form, I thought it may have been caused by a foreach loop in the PHP but this is not the case.
I have removed the jQuery functions and it works perfectly each time without any duplicates on normal PHP submit.
I have manually processed the entries via jQuery instead of serialize but as there is a dynamic array via PHP I still used serialize on that array, this produced the duplicates as described above.
I have searched the issue for a number of days but cannot find anything definitive to clear up the issue, all suggestions on blogs and forums that looked to be related did not work, I have tried around 10-15 different options.
The combination of all of this leads me to believe the issue is coming from the jQuery serialize and/or ajax functions but my eyes have become glazed each time I look at this code now.
I am also considering placing the form in an external file and reloading it fresh via ajax or cleaning the form setting it back to defaults via jQuery for each new entry required however I do not believe either of these approaches will solve the problem.
Any help is greatly appreciated, thanks in advance for the help!
jQUERY code
<script>
$(document).ready(function() {
$('.fileupload').fileupload('name:logo');
$('.help-inline').hide();
$("#btn_process").click(function() {
$('form').submit(function() {
$('.help-inline').hide();
var company_name = $("#company_name").val();
if (company_name === "") {
$("div#name_group").addClass("error");
$("span#name_error").show();
return false;
}
var dataString = $('form').serialize();
$.ajax({
type: "POST",
url: "inc/addcompany.php",
data: dataString,
success: function(html) {
if(html === 'success')
{
$('#message')
.addClass("label label-success")
.css("margin-bottom","20px")
.html("<h3>Login successful</h3><p>Company added</p>")
.slideDown(1500, function() {});
}
else
{
$('#message')
.addClass("label label-important")
.css("margin-bottom","20px")
.html("<h3>Error</h3><p>There was an error, please check the information and try again</p>")
.slideDown(1500, function() {});
$("div#name_error").addClass("error");
$("span#name_error").show();
$("div#type_error").addClass("error");
$("span#type_error").show();
return false;
}
}
});
return false;
});
});
});
</script>
HTML markup
<form class="form-horizontal" id="add_company" method="POST" action="">
<fieldset>
<div id="message"></div>
<div id="name_group" class="control-group">
<label class="control-label" for="company_name">Company name </label>
<div class="controls">
<input type="text" id="company_name" name="company_name" />
<span id="name_error" class="help-inline">This needs to be more than 3 characters</span>
</div>
</div>
<div id="type_group" class="control-group">
<label class="control-label">Company type </label>
<div class="controls">
<?
$sql = "SELECT description,id FROM types ORDER BY description";
$qry = mysql_query($sql) or die("ERROR: could not get company types => ".mysql_error());
while($company_type = mysql_fetch_array($qry)) {
echo '
<label class="checkbox inline"><input type="checkbox" name="type[]" value="'.$company_type['id'].'" /> '.$company_type['description'].' </label>';
}
?>
<span id="type_error" class="help-inline">Please select a minimum of 1 type</span>
</div>
</div>
<div id="website_group" class="control-group">
<label class="control-label" for="website">Website </label>
<div class="controls">
<input type="text" id="website" name="website" placeholder="www.something.com" />
</div>
</div>
<div id="logo_group" class="control-group">
<label class="control-label">Logo </label>
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 50px; height: 50px;"><img src="/img/50x50.png" /></div>
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 50px; height: 50px;"></div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span>
<span class="fileupload-exists">Change</span>
<input type="file" /></span>
Remove
</div>
</div>
</fieldset>
<input type="hidden" name="action" value="add_company" />
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" name="btn_process" id="btn_process">Save changes</button>
</form>
The PHP processor
$error = false;
$error_company_name = false;
$error_type = false;
$error_website = false;
$company_name = $_REQUEST['company_name'];
$type = $_REQUEST['type'];
$website = $_REQUEST['website'];
$logo = $_REQUEST['logo'];
if(empty($company_name)) {
$error = true;
$error_company_name = true;
}
include_once('db.php');
$sql = "SELECT description,id FROM company_types";
$qry = mysql_query($sql) or die("ERROR: could not get company types => ".mysql_error());
$type_count = 0;
while($array = mysql_fetch_array($qry)) {
$type_count = $type_count+1;
}
if($type_count == 0) {
$error = true;
$error_type = true;
}
$ic = 0;
foreach($_REQUEST['type'] as $item) {
$ic = $ic+1;
}
if($ic == 0) {
$error = true;
$error_type = true;
}
if(isset($website) && $website != ' ') {
$url = 'http://'.$website;
if(!filter_var($url, FILTER_VALIDATE_URL)) {
$error = true;
$error_website = true;
}
}
if($error == false) {
$sql = "INSERT INTO company_list (name,website,logo) VALUES('$company_name','$website','$logo')";
$qry = mysql_query($sql) or die ("ERROR: could not add company => ".mysql_error());
$company_id = mysql_insert_id($link);
if($company_id == '' || $company_id == null || empty($company_id)) {
echo 'fail';
exit;
}
foreach($_REQUEST['type'] as $company_type) {
$sql = "INSERT INTO companies_types (companies_id,type_id) VALUES('$company_id','$company_type')";
$qry = mysql_query($sql) or die("ERROR: could not link company type: => ".mysql_error());
}
echo 'success';
}
Add $('form').unbind('submit'); immediately above this line: $('form').submit(function().
I found this solution here: https://stackoverflow.com/a/668354/300575
Note: I verified that this works by copying your code and testing it on my server.
It may be a patch and dont know if it will work but there is a jQuery ajaxStop which can be called at the success call back.

Categories