So basically I am trying to upload a Model and Serial number into a database only on POST but SOMETIMES, not all the time, it will duplicate the entry in the database even though I only hit submit once, once submitted, the text field goes blank as it should so how is it adding it more than once?
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "database";
if ($_POST['submit'])
{
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$mod = mysqli_real_escape_string($con,$_POST['model']);
$sn_num = mysqli_real_escape_string($con,$_POST['sn']);
$sql = "INSERT INTO rma_product (m_type,pro_sn) VALUES ('$mod','$sn_num')";
if ($con->query($sql) === TRUE) {
$success = "New record created successfully";
} else {
$success = "Failed!";
}
$con->close();
}
?>
<form method="post" name="sn_upload" id="sn_upload">
<div>
<label for="model">Model: </label><select id="model" name="model" title="Model" />
<option value="ModelA">ModelA</option>
</select><br><br>
<label for="sn">Serial Number: </label><input type="text" id="sn" name="sn" placeholder="Serial Number" pattern="[a-zA-Z0-9]{11,13}"/><br><br>
<input name="submit" type="submit" value="Submit" />
<?php if( $success) echo "<div>".$success."</div>";?>
</div>
</form>
<script>
(function() {
var input = document.getElementById('sn');
var form = document.getElementById('sn_upload');
var elem = document.createElement('div');
elem.id = 'notify';
elem.style.display = 'none';
form.appendChild(elem);
input.addEventListener('invalid', function(event){
event.preventDefault();
if ( ! event.target.validity.valid ) {
input.className = 'invalid animated shake';
elem.textContent = 'Serial Number must be between 11 and 13 characters and DO NOT include spaces.';
elem.className = 'error';
elem.style.display = 'block';
}
});
input.addEventListener('input', function(event){
if ( 'block' === elem.style.display ) {
input.className = '';
elem.style.display = 'none';
}
});
})();
</script>
Related
I want to submit DATE to a database if the user has unchecked check box & selected date manually & if the user has checked the checkbox the current date will be submitted to a database.
Check screenshot for better understanding checked unchecked
form :
<form action="insert.php" method="POST">
<div class="form-group">
<label for="Camp">Start Campaign Immediately: </label>
<input type="checkbox" id="myCheck" name="Camp" onclick="onCheck(this);">
<div class="alert alert-danger" role="alert" id="campError"></div>
</div>
<div class="form-group">
<label for="sel1">Campaign Start Date:</label>
<input type="date" name="date" value="EnrollDate" id="date" onchange="checkDate(this);">
<div class="alert alert-danger" role="alert" id="dateError"></div>
<br>
<br>
<div class="form-group">
<button type="submit" id="btnEnter" name="b1" value="b1" class="btn btn-default">Submit</button>
</div
script :
<script>
function onCheck(checkbox) {
var dateElement = document.getElementById('date');
dateElement.disabled = checkbox.checked;
if (checkbox.checked) {
//dateElement.value = new Date().toISOString().substr(0, 10);
dateElement.valueAsDate = new Date();
}
else
dateElement.value = '';
}
var listA = [{name:'White', value:'White'}, {name:'Red', value:'Red'}, {name:'Black', value:'Black'}, {name:'Grey', value:'Grey'}];
var listB = [{name:'White', value:'White'}, {name:'Black', value:'Black'}];
$(document).ready( function() {
$("input[name='chk']").on('click',function() {
if($(this).is(':checked') && $(this).val() == '1')
{
$('#describ').empty()
$.each(listA, function(index, value) {
$('#describ').append('<option value="'+value.value+'">'+value.name+'</option>');
});
}
else if($(this).is(':checked') && $(this).val() == '2')
{
$('#describ').empty()
$.each(listB, function(index, value) {
$('#describ').append('<option value="'+value.value+'">'+value.name+'</option>');
});
}
else
{
}
});
});
</script>
insert.php :
<?php
if(isset($_POST["b1"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$title = $_POST['title'];
$chk = $_POST['chk'];
$describ = $_POST['describ'];
$Camp = $_POST['Camp'];
$date = $_POST['date'];
}
if ((!empty($name) && !empty($email) && !empty($title) && !empty($chk) && !empty($chk) && !empty($describ) && !empty($Camp) && !empty($date)))
{
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "form";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From form Where email = ? Limit 100";
$INSERT = "INSERT Into form (name, email, title, chk, describ, Camp, date) values(?, ?, ?, ?, ?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssssssi", $name, $email, $title, $chk, $describ, $Camp, $date);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>
The problem is date and checkbox value not getting inserted to the database. I'm using localhost/phpmyadmin/
I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},
I had previously mentioned about my registration code. I now want to save the image name into the database.The image is to be uploaded using file upload. The validation is done using jquery and the form has to be submitted using ajax.Now i had read that file uploads cannot be performed using ajax.And that is the problem with my code.
Following is my code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
function ValidateEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)| (([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
$(document).ready(function(){
$('#submit').on('click', function() {
//e.preventDefault();
valid = true;
if ($('#name').val() == '') {
alert ("please enter your name");
//$('#errorMsg1').css('color','red');
//$('#errorMsg1').html('Please enter your name');
//document.getElementById("errorMsg1").innerHTML = "You must enter a name";
valid = false;
}
if ($('#email').val() == '') {
alert ("please enter your email");
//$('#errorMsg2').css('color','red');
//$('#errorMsg2').html('Please enter your emailid');
//document.getElementById("errorMsg2").innerHTML = "You must enter a email";
valid = false;
}
if (!ValidateEmail($("#email").val())) {
alert("Invalid email address.");
//document.getElementById("errorMsg2").innerHTML = "Invalid email address.";
}
if ($('#bday').val() == '') {
alert ("please enter your birth date");
//$('#errorMsg3').css('color','red');
//$('#errorMsg3').html('Please enter your birth date');
//document.getElementById("errorMsg3").innerHTML = "You must enter your birth-date";
valid = false;
}
if ($('#gender').val() == '') {
alert ("please select your gender");
//$('#errorMsg4').css('color','red');
//$('#errorMsg4').html('Please select your gender');
//document.getElementById("errorMsg4").innerHTML = "You must select your gender";
valid = false;
}
if ($('#image').val() == '') {
alert ("please select an image");
//$('#errorMsg5').css('color','red');
//$('#errorMsg5').html('Please select an image');
//document.getElementById("errorMsg5").innerHTML = "You must select an image";
valid = false;
}
});
return false;
$("#multiform").submit(function (e)
{
var formObj=$(this);
var formURL=formObj.attr("action");
var formData=new formData(this);
$ajax({
URL:formURL,
type:'POST',
data:formData,
mimeType:"multipart/form-data",
contentType:false,
cache:false,
processData:false,
success:function(data,textStatus,jqXHR){
},
error:function(jqXHR,textStatus,errorThrown){
}
});
e.preventDefault();
e.unbind();
}
);
return true;
$("#multiform").submit();
});
</script>
</head>
<body>
<form name="multiform" id="multiform" action="save_data.php" method="POST" enctype="multipart/form-data">
<h4>Name:</h4> <input type="text" name="name" id="name" autofocus>
<br><br>
<h4>E-mail:</h4> <input type="text" name="email" id="email" autofocus>
<br><br>
<h4>Birth-date:</h4> <input type="text" name="bday" id="bday" autofocus>
<br><br>
<h4>Gender:</h4>
<input type="radio" name="gender" id="gender" value="female" autofocus>Female
<input type="radio" name="gender" id="gender" value="male" autofocus>Male
<br><br>
Select Image:<input type="file" name="image" id="image"><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
save_data.php:
<!DOCTYPE html>
<html>
<body>
<?php
error_reporting( E_ALL & ~E_NOTICE );
// define variables and set to empty values
$name = $email = $bday = $gender = $image="";
//$image=$_FILES["image"]["name"];
if(isset($_POST['submit'])){
$name = $_POST["name"];
$email = $_POST["email"];
$bday=$_POST["bday"];
$gender = $_POST["gender"];
$image =$_POST["image"];
$servername = "localhost";
$username = "mvs1";
$password = "";
$dbname="scootsy_categories";
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$sql = "INSERT INTO user_details(name,email,bday,gender,image) VALUES ('$name','$email','$bday','$gender','$image')";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
//if($name !="" || $email !="" || $bday !="" || $gender !="" || $image !="" )
//{
// $sql="DELETE FROM user_details where name='$name' || email='$email' || bday='$bday' || gender='$gender' || image='$image'";
//}
$conn->close();
}
echo "Successful";
?>
</body>
</html>
You can't save images into a database, but you can save the path url and before you save the image into a folder with php. For do this, you have to modify your ajax code and your php file because for do all this, we have to use $_FILES for extract the name, type, size and temp_folder for move it into a filder.
Rewrite your ajax code.
Get with $_FILES the properties of the file
<script type="text/javascript">
$('body').on('click','#submit', function() {
$.ajax({
type:'POST',
url:'save_data.php',
data: new FormData($('#your_id_form')[0]),
contentType:false,
cache:false,
processData:false,
success:function(upload) {
$('#multiform').html(upload):
}
});
});
</script>
<form id="your_id_form" method="POST" action="save_data.php">
<input type="name" placeholder="Your name">
<input type="file" name="file">
<input type="button" id="submit">
</form>
<div id="multiform"></div>
//save_data.php
$name = $_POST['name'];
$file_name = $_FILES['file'];
$file_size = $file_name['size'];
$file_type = $file_name['type'];
$file_tmp = $file_name['tmp_name'];
list($name,$type) = explode('/',$file_type);
$save_temp = $file_tmp;
//create a new folder named images into your root page
$new_path = 'images/'.$name.$type;
//we move the file from the temporal folder to a new folder
move_uploaded_file($save_temp, $new_path);
$file_url = 'images/'.$file_type;
$sql = "INSERT INTO database (name,file_url) VALUES ('$name', '$new_path')";
//do stuffs for connect your query to your database
echo 'Uploaded!';
?>
I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"
I'm trying to submit Multiple Form Items from HTML using Java-script into mySQL via AJAX request. I can get one field to update but not the other 2. I've commented out the other code I believed would aid in this but was not working.
HTML part:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
parameters = 'fname='+document.getElementById('fname').value;
xmlhttp.open("POST", "update.php", true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
} ;
</script>
</head>
<body>
First Name: <input class="work" type="text" id="fname" ><br>
Middle Name: <input class="work" id="mname" type="text"><br>
Last Name: <input class="work" id="lname" type="text"><br>
<input type="button" value="Submit" onclick="insert();">
<div id="message"></div>
</body>
</html>
PHP part:
<?php
//require 'connect.midasproject.php';
$conn_error = 'could not connect.';
$dbhost = "localhost";
$dbname = "mastergolddb";
$dbuser = "root";
$dbpass = "";
if (!#mysql_connect("$dbhost", "$dbuser", "$dbpass")||!#mysql_select_db ("$dbname")) {
die($conn_error);
} else {
echo 'connected.';
}
$fname = $_POST['fname'];
//$mname = $_POST['mname'] ;
//$lname = $_POST['lname'];
if (!empty($fname)) {
$query = "INSERT INTO `customers` VALUES ('','$fname','joe','blow')";
if ($query_run = mysql_query($query)) {
echo 'data inserted.' ;
} else {
echo 'Query failed.';
}
}
?>
you need to pass all 3 values to the ajax function. you seem to be passing just fname here
parameters = 'fname='+document.getElementById('fname').value;