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.
Related
I have this code for search in my database, I use a barcode scanner (work like a keyboard), when I scan a barcode the input text shown perfectly, but I need to press MATCH to do the enter function, I want to submit it automatically after the barcode scanner scan a code and not to press MATCH.
<html>
<body>
<div class="container pt-5">
<div class="row">
<form method="POST" action="match.php" autocomplete="off">
<div class="form-group">
<label>Scan:</label>
<input type="text" id="no" name="no" class="form-control" required>
</div>
<div ></div>
<button class="btn btn-info" name="sub" type="submit">MATCH</button>
</form>
</div>
</div>
</body>
</html>
<?php
include 'includes/conn.php';
if (isset($_POST['sub'])) {
$sca=trim($_POST['no'],"");
$flag=0;
$credentials="";
$password="";
$firstname="";
$lastname="";
$new2 ="SELECT * FROM `voters`";
$res2=mysqli_query($conn, $new2);
while($row=mysqli_fetch_array($res2)){
//echo $row['number'].'<br>';
// if($row['number']){
if($row['credentials'] == $sca){
$flag=1;
$credentials=$row['credentials'];
$password=$row['password'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}if ($flag==1) {
echo "<div class='container'><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'><div class='alert alert-success d-flex justify-content-center mt-3'>".
'<br><b>Votante:</b>'.' '.$id.
'<br><b>Registro:</b>'.' '.$credentials.
'<br><b>Contraseña:</b>'.' '.$password.
'<br><b>Nombre:</b>'.' '.$firstname.
'<br><b>Apellidos:</b>'.' '.$lastname.
"</div></div></div><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'>" ;
return;
}
else{
echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Product Not Found</div></div>";
return;
}
}
mysqli_close($conn);
?>
We had to work with barcode scanners a while ago, where we had a similar request, so I hope I can help here. Most simple barcode scanners just enter the scanned code and append a new line.
As stated in the comments you need some JavaScript in order to do that. We used the jquery library. Like CBroe said, you need to find the correct event, to use. We tried different events and found the "change" event to be the best suitable one for us.
Our case was a little more complex, because we had multiple fields and had to make ajax requests, so I tried to reduce our script to something that may be a good starting point for you:
$(document).ready(function() {
$('#no').change(function () { //if content of field with id #no changes do stuff
let value = $(this).val();
const minlength = 5;
if (value.length >= minlength) {
$( "#scanform" ).submit(); //submit form with id scanform
}
});
});
Pleas note, that this script assumes you add the id "scanform" to your form tag.
I have this code with multiple forms within the same page:
test1 page:
<select id="mudar_produto">
<option value="#produto_1">Novo Produto Higiene</option>
<option value="#produto_2">Entrada de Produtos Higiene</option>
<option value="#produto_3">Novo Produto Nutricia</option>
</select>
<section class="hide-section" id="produto_1">
<form id="form3" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
</div>
</fieldset>
<button type="submit" name="submit" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_2">
<form name="form4" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Entrada de Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Data Entrada">Data Entrada</label></strong>
<input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Produto">Produto</label></strong>
<select id="first_dd" name="Produto" style="width:250px" required>
<option></option>
<?php
$sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>';
$valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']);
}
?>
</select>
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<select id="second_dd" name="Unid" style="width:150px" required>
<option></option>
<?php
foreach ($valencia as $key => $value) {
echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>';
}
?>
</select><br>
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Quantidade">Quantidade</label></strong>
<input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
</div>
<div class="campo">
<strong><label for="Preço">Preço</label></strong>
<input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">
</div>
</fieldset>
<button type="submit" name="submit1" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_3">
<form id="form3" name="form3" action="./teste2" method="POST" onsubmit="return form_validation()" >
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Nutricia</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="ProdNutricia" name="ProdNutricia" style="width:350px" required="" size="120" />
</div>
</fieldset>
<button type="submit" name="submit2" class="botao submit">Registo</button>
</form>
</section>
In the page teste2 I make the insertion of the data in the table of the database:
<script language="javascript" type="text/javascript">
document.location = "teste1";
</script>
<?php
if(isset($_POST['submit'])){
$name = $_POST['DescricaoProd'];
$unid = $_POST['DescricaoUnid'];
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit1'])){
$data = $_POST['DataEntrada'];
$produto = $_POST['Produto'];
$unidade = $_POST['Unid'];
$quantidade = $_POST['Quantidade'];
$preco = $_POST['Preco'];
$sql = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";
if ($conn->query($sql) === TRUE);
$sql1 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit2'])){
$name = $_POST['ProdNutricia'];
$sql = "INSERT INTO ProdNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
Everything is working correctly with the insertion of data in the table, but when I do the insertion and does the header ("Location: teste1"); closes the form I was filling out and I want to keep it open, since I may have to insert several types of products on the same form.
Some explanation to start with:
I have cleaned up your HTML markup. You may have gotten the look you desired, but the markup is badly broken. A good editor will help you with making a well-formed document that validates.
I've used Bootstrap for styling. Foundation is another good choice.
JQuery is used as the basis for Javascript event monitoring and AJAX
This is not copy and paste code. It's untested; it's purpose is to point you in the right direction.
The code is commented to help you understand what it's doing.
Since this is how SO is showing the code, we start off with the javascript and the HTML:
// this delays execution until after the page has loaded
$( document ).ready(function() {
// this monitors the button, id=submit-form-1, for a click event
// and then runs the function, submitForm1()
$('#submit-form-1').on('click', function() {
submitForm('#form1');
});
// could be repeated for another form...
$('#submit-form-2').on('click', function() {
submitForm('#form2');
});
});
// this function does an AJAX call to "insert.php".
// it expects a reply in JSON.
function submitForm(whichForm) {
var datastring = $(whichForm).serialize();
// see what you're sending:
alert('You would be sending: ' + datastring);
$.ajax({
type: "POST",
url: "insert.php",
data: datastring,
dataType: "json",
success: function(data) {
if(data.status=='success') {
alert('successfully uploaded');
} else {
alert('failed to insert');
}
},
error: function() {
alert("This example can't actually connect to the PHP script, so this error appears.");
}
});
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="produto_1">
<!--
note that the form is identified with id="form1".
"id" has to be unique. Nothing else can have id="form1".
There are no action nor method attributes,
since AJAX is submitting the form contents.
-->
<form class="form-horizontal" id="form1">
<!--
field named "action" will be used in PHP script
-->
<input type="hidden" name="action" value="insert_form_1" />
<!-- use CSS for styling, not <center>, <strong>, etc. -->
<h1 class="text-center">Produtos de Higiene</h1>
<div class="form-group">
<label for="DescricaoProd" class="col-sm-2 control-label">Nome do Produto</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoProd" name="DescricaoProd" required />
</div>
</div>
<div class="form-group">
<label for="DescricaoUnid" class="col-sm-2 control-label">Unidade</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoUnid" name="DescricaoUnid" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<!--
button type is button, not submit.
Otherwise the form will try to submit.
We want the javascript to submit, not the form.
-->
<button type="button" id="submit-form-1" class="btn btn-success">Registo</button>
</div>
</div>
</form>
</section>
<!-- set up another form in the same way... -->
<form id="form2">
<input type="hidden" name="action" value="insert_form_2" />
...
<button type="button" id="submit-form-2">submit form 2</button>
</form>
The above markup and javascript should make an AJAX POST request to insert.php, and listen for a reply.
insert.php
<?php
/**
* note: It is a good practice to NEVER have anything before the <?php tag.
*
* Always try to separate logic from presentation. This is why you should
* start with PHP on the top, and never do any output until you are done
* with processing. Better yet, have separate files for logic and presentation
*
*/
// if $_POST doesn't have ['action'] key, stop the script. Every request will have
// an action.
if(!array_key_exists('action', $_POST)) {
die("Sorry, I don't know what I'm supposed to do.");
}
// database initialization could (should) go on another page so it can be reused!
// set up PDO connection
// this section credit to https://phpdelusions.net/pdo
// use your credentials here...
$host = '127.0.0.1';
$db = 'your_db_name';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// helpful initializations, such as default fetch is associative array
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// instantiate database
$pdo = new PDO($dsn, $user, $pass, $opt);
// end database initialization
// whenever you have to do something over again, break it out into a function
// this function prevents warnings if the variable is not present in $_POST
function get_post($var_name) {
$out = '';
if(array_key_exists($var_name,$_POST)) {
$out = $_POST[$var_name];
}
return $out;
}
// assign variables
$action = get_post('action');
$name = get_post('DescricaoProd');
$unid = get_post('DescricaoUnid');
// All output of this script is JSON, so set the header to make it so.
// There can be NO output before this!
// Not even a blank line before the <?php start tag.
header('Content-Type: application/json');
// take action based on value of "action".
if($action=='insert_form_1') {
$error = false;
$output = array('message' => 'success');
// Use placeholders, never (NEVER NEVER NEVER) php variables!
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
// note, I just repeated myself, so this probably should be refactored...
// send a message back to the calling AJAX:
if($error) {
$output = array('status' => 'failed');
} else {
$output = array('status' => 'success');
}
print json_encode($output);
die; // nothing more to do
}
// you could have additional actions to perform in the same script.
// or, you could use different files...
if($action=='insert_form_2') {
// do insert for form 2
}
// etc.
I'm trying to get multiple checked checkbox value data added to mysql with php without reloading the form page and show confirmation message in div on form page. At the moment, showing on div works but data is not being sent.
I already have done another similar one which I had almost the same code that had the input as text area so I changed that part and it works but the this one is not working. Could anyone give me help here?
form is in vote.php:
<html>
<form action="vote_received.php" method="post" target="" id="vote-submit">
<input type="hidden" name="recieved-date" id="todayDate" />
<input type="hidden" name="user-occup" id="user-occup" value="<?php $_SESSION['occupation']; ?>" />
<input type="checkbox" name="voting[]" value="How might we improve driver facilities such as lunch rooms or break rooms?" id="voting_1">
<label for="voting_1">How might we improve driver facilities such as lunch rooms or break rooms?</label>
<input type="checkbox" name="voting[]" value="How might be increase driver security at night time?" id="voting_2">
<label for="voting_2">How might be increase driver security at night time?</label>
<input type="checkbox" name="voting[]" value="How might we change the on-call communication with management?" id="voting_3">
<label for="voting_3">How might we change the on-call communication with management?</label>
<input type="checkbox" name="voting[]" value="How might we enhance the passenger conflict management system?" id="voting_4">
<label for="voting_4">How might we enhance the passenger conflict management system?</label>
<br><br>
<input type="submit" name="submit" value="Submit" class="btn align-right"></form>
<script>
$("#vote-submit").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = $messages.val(),
url = $form.attr('action');
var posting = $.post(url, { submission : message_value});
posting.done(function(data) {
/* Put the results in a div */
$("#vote_success").html('<h2>THANK YOU!</h2><p>Thank you for your voting. Meeting invitations will be send out on December 7th, 2017.');
/* Hide form */
$form.hide();
});
});
</script>
</html>
the vote_received.php is:
<?php
session_start();
if(isset($_POST['vote-submit'])) {
$voteArray=$_POST['voting'];
$conn = mysqli_connect($servername, $username, $password, $database);
if(is_null($voteArray)) {
echo("<p>You didn't select any topic.</p>\n");
} else {
$N = count($voteArray);
for($i=0; $i < $N; $i++) {
$var1 = $voteArray[$i];
$jobTitle = $_SESSION['occupation'];
$sql = "INSERT INTO vote_response (occupation, voting,
created) VALUES('$jobTitle', '$var1', now())";
$success = mysqli_query($conn, $sql);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $var1;
$conn->close();
}
}
}
?>
Thank you very much!
try to change this part of your code
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = [],
url = $form.attr('action');
$.each($messages, function(idx, val){
message_value.push($(val).val());
});
var posting = $.post(url, { submission : message_value});
on further reading of your code, try to change this part of you code also:
if(isset($_POST['submission'])) {
$voteArray=$_POST['submission'];
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']
This is pretty specific and I have not found an answer yet.
I am writing a script to check if a name is already input into the SQL server using JQuery $.POST.
The front end looks like this:
register.php
<div id="container" class="container">
<div id="wrapper" class="wrapper">
<div id="title" class="title">
Welcome to Taskar!
</div>
<div id="login" class="login">
<form method="post" action="registermembers.php">
<div id="exists">
Register Your Company Below:
</div>
<input type="text" id="company" name="company" value="Company Name"/> <br />
<br />
<input type="text" id="password" name="password" value="Default Password"/> <br />
<input type="submit" name="submitcompany" value="Submit" />
</form>
<script>
$(document).ready(function() {
$('#company').keyup(function() {
var $company = $(this).val();
var $reg = $('#exists').html();
$.post('include/reg_post.php', { company: $company, reg: $reg }, function(company) {
$('#exists').html(company);
});
});
});
</script>
</div>
</div>
</div>
The backend code looks like this:
reg_post.php
<?php
include 'include/db.php';
$reg = $_POST['reg'];
$company = $_POST['company'];
$email_hash = $_COOKIE['email_hash'];
$password = $_COOKIE['password'];
$sql = "SELECT * FROM taskar_employee WHERE (company = '$company')";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
} ?>
Now, the problem I am having is, when I am testing this, it works fine all the way up to when I type in a company name that is in the database. It shows me that the company is already registered. When I press backspace or type another letter, it still tells me the company still exists, though it obviously would not.
It seems that the if statement wants to stop the $.post feature from continuing after it gets the opposite statement?
What do you guys think?
Your problem lies in the way you're using your $reg variable.
$reg contains the HTML contents of the #exists div, so it's "Register your Company Below:" to begin with. But, once you've hit a company name that does exist, you replace that HTML with "This Company Already Exists!". From that point on, $reg, on both the JavaScript and PHP sides, is always "This Company Already Exists!" (since you always pass $reg in your POST).
It would probably be much easier if the contents of that div weren't passed to or handled by the PHP code at all. It'd be simpler if your PHP script just returned "1" if the company existed, and "0" if not (or some other equally simple flags).
Then, on the JavaScript side, you could just do:
$.post('include/reg_post.php', { company: $company }, function(exists) {
var message;
if (exists === '1') {
message = 'This Company Already Exists!';
}
else {
message = 'Register Your Company Below:';
}
$('#exists').html(message);
});
You're passing $('#exists').html(); to be returned in the event that the company is not found. The problem is, in the event that the company is found, you replace the html within #exists. Then the next time you call the post you pass this text back along so in this case:
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
}
your $reg is now set to This Company Already Exists! so regardless of what happens you're going to return that text.