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!';
?>
Related
I'm working on a signup form in PHP. The form is a div which opens when you click on a button. Here's my code:
if(!$fieldsFilled){
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
This all executes after my form is submitted:
if (isset($_POST['signUp']))
Full PHP code:
<?php require 'dbconnect.php'; ?>
<?php
//Error message variable declarations
$unmatchedPasswordsError = "";
$unfilledFormsError = "";
$emailError = "";
//If sign up submit POST recieved
if (isset($_POST['signUp']))
{
//Start session
session_start();
$email = $connection->real_escape_string($_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows)
{
$emailInUse = true;
}
else
{
$emailInUse = false;
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suVerifyPassword', 'suDisplayName');
$fieldsFilled = true;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$fieldsFilled = false;
}
else
{
$fieldsFilled = true;
}
}
if ($emailInUse)
{
$emailError = "The email is already in use.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
if(!$fieldsFilled)
{
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "The email is not valid.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Check for unverified password
if ($_POST['suPassword']!= $_POST['suConfirmPassword'])
{
$unmatchedPasswordsError = "The passwords do not match.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Variable declaration for sign up POST values
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//Insert POST values into database
$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
//Redirect to 'email sent' webpage
header('Location: emailSent.php');
}
}
}
}
}
//If log in submit POST recieved
if (isset($_POST['logIn']))
{
//Variable declaration for log in POST values
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//Search for log in credentials in dabase
$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
//TODO: CHECK FOR REMEMBER ME CHECK
session_start();
$_SESSION['userID'] = $row['userID'];
}?>
HTML sign up div/form code:
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<?php
echo '<br><font class="text-error" id="email-error">',$emailError,'</font>';
?>
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<?php
echo '<br><font class="text-error" id="passwords-unmatched-error">',$unmatchedPasswordsError,'</font>';
?>
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<?php
echo $unfilledFormsError;
?>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
The "test passed" does log to the console, however the div is not showing after the page refresh (due to form submission). Any help is appreciated! Thank you so much!
I have customized as your requirement and database connection i have used
Mysqli replace whatever you want also change database credentials.
Full code will be in same page. Try and comment if you don't understand anything.
<?php
session_start();
//require 'dbconnect.php';
$connection=mysqli_connect("localhost","root","","test"); // I have use it for testing
$errors = array();
if (isset($_POST['signUp'])) {
$email = mysqli_real_escape_string($connection, $_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
//email check
if(mysqli_num_rows($result)>0){
$errors[] = "The email is already in use.";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "The email is not valid.";
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suConfirmPassword', 'suDisplayName');
foreach($required as $field){
if (empty($_POST[$field])){
$errors[] = $field." Cannot be empty.";
}
}
if(count($errors)==0){
if($_POST['suPassword']!=$_POST['suConfirmPassword']){
$errors[] = "The passwords do not match.";
}else{
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
$sql = mysqli_query($connection, "INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
if($sql){
header('Location: emailSent.php');
}else{
$errors[] = "Failed to insert.";
}
}
}
}
if (isset($_POST['logIn'])){
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$result = mysqli_query($connection, "select * from users where email = '$liEmail' AND password = '$liPassword'");
if($result){
$row = mysqli_fetch_assoc($result);
$_SESSION['userID'] = $row['userID'];
}
}
?>
<?php
if(!empty($errors)){
foreach ($errors as $value) {
echo "<span style='color:red;'>".$value."</span><br>";
}
}
?>
<button type="button" id="showSignup">Show Sign-up</button><br><br>
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
<?php if(isset($_POST['signUp']) && count($errors)>0){ ?>
$('#home-sign-up-box').show();
<?php }elseif(isset($_POST['signUp']) && count($errors)==0){ ?>
//$('#home-sign-up-box').hide();
<?php }else{?>
//$('#home-sign-up-box').show();
<?php }?>
$("#showSignup").click(function(){
$('#home-sign-up-box').toggle();
visible_check();
});
visible_check();
});
function visible_check(){
var isVisible = $( "#home-sign-up-box" ).is( ":visible" );
if(isVisible){
$("#showSignup").html("Hide Sign-up");
}else{
$("#showSignup").html("Show Sign-up");
}
}
</script>
I've been trying to pass the information to the next webpage only when all the fields that need to be filled are filled.However regardless if the fields are filled or not , the information is still passed to the next webpage.
This is the webpage that has the fields
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Book A Table</title>
</head>
<body>
<h1>Book A Table</h1>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $numErr=$dateErr = $timeErr = $personsErr="";
$name = $email = $num= $date = $time = $persons = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["num"])) {
$numErr = "Number is required";
} else {
$num = test_input($_POST["num"]);
if (!preg_match("([0-9])", $num)) {
$numErr = "Enter numbers only";
}
}
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date = test_input($_POST["date"]);
}
if (empty($_POST["time"])) {
$timeErr = "Time is required";
} else {
$time = test_input($_POST["time"]);
}
if (empty($_POST["persons"])) {
$personsErr = "Number of persons is required";
} else {
$persons = test_input($_POST["persons"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
//directs all the entered information below to DBInput.php
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Full Name<br> <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail<br> <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Contact Number<br> <input type="text" name="num">
<span class="error">*<?php echo $numErr;?></span>
<br><br>
Reservation Date<br> <input type="date" name="date">
<span class="error">*<?php echo $dateErr;?></span>
<br><br>
Reservation Time<br>(Mon - Thur: 18:00 - 23:00 Fri - Sun: 12:00 - 00:00)<br> <input type="time" name="time">
<span class="error">*<?php echo $timeErr;?></span>
<br><br>
Number of Persons<br> <input type="text" name="persons">
<span class="error">*<?php echo $personsErr;?></span>
<br><br>
Comments<br><textarea name="comment" rows="5" cols="40"></textarea><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if($name!=""&&$email!=""&&$num!=""&&$date!=""&&$time!=""&&$persons!=""){ ?>
//directs all the entered information below to DBInput.php
<form action="DBInput.php" method="POST" />
<?php } ?>
</body>
</html>
This is the website that receives the information from the fields and stores them in a database
<?php
$servername = "localhost";
$username = "Client";
$dbname= "webassigment";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//stores the values entered in book.php in each value
$value1=$_POST['name'];
$value2=$_POST['email'];
$value3=$_POST['num'];
$value4=$_POST['date'];
$value5=$_POST['time'];
$value6=$_POST['persons'];
$value7=$_POST['comment'];
//puts the values in each respective database field
$sql = "INSERT INTO booking (Name,Email, ContactNumber,ReservationDate ,Reservationtime, NumberOfPeople,Comment)
VALUES ('$value1', '$value2', '$value3','$value4','$value5','$value6','$value7')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo "Connected successfully";
?>
You are trying to do some weird type of validation. I've seen "custom" form validations but like this one never.
You've complicated way too much the things.
Usually the validation is made by javascript or jQuery and for posting the variables only if all are filled you can put the ajax request into a conditional statement like this :
var name = $('#name').val();
var email = $('#email').val();
var num = $('#num').val()
var dqte = $('#date').val()
var time = $('#time').val()
var persons = $('#persons').val()
var comment = $('#comment').val()
if(name !== null && email !== null && ... put here all your conditions ) {
form_data.append('file', file_data);
$.ajax({
url: 'DBInput.php', // point to server-side PHP script
cache: false,
contentType: false,
processData: false,
data: {name: name, email: email, ... },
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
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 will be on the point. But anyways, THANKS IN ADVACE.
So basically When I submit the form I made, it submits and stuff, but it redirects the page to the PHP file, and shows this on the browser (not as an alert) :
{"status":"success","message":"Yer message was sent."}
when the data is successfully validated, and shows this
{"status":"fail","message":"Invalid name provided."}
when the form doesn't validate. What I want, is that when the form submits, it stays on the same page and if status is true or false, it should alert the message in the array.
I'll write down the scripts and the file names are: index.html, script.js and post.php
INDEX.HTML
<form action='post.php' id='post_message' name='post_message' method="post">
<p>
<input id='email' type="email" class='post' placeholder="Email goes in here.(Required) " class="width" name="email">
<br>
<input id='fname' type="text" class='post' placeholder="First Name (Required) " name="FirstName"><br>
<input id='lname' type="text" class='post' placeholder="Last Name (Required) " name="LastName"><br>
<input id='website' type="url" class='post' placeholder="Website? (Optional!)" class="width" name="website"><br>
<textarea id='message_text' placeholder="Your Message goes here. (Required, DUH!) " name='message'></textarea>
</p>
<button type="submit" class="submit" id='btnPost'></button>
<input type="hidden" name="action" value="post_message" id="action">
</form>
SCRIPT.JS
function clearInputs(){
$("#fname").val('');
$("#lname").val('');
$("#email").val('');
$("#website").val('');
$("#message_text").val('');
}
$('#btnPost').click(function() {
var data = $("#post_message").children().serializeArray();
$.post($("#post_message").attr('action'), data, function(json){
if (json.status == "fail") {
alert(json.message);
}
if (json.status == "success") {
alert(json.message);
clearInputs();
}
}, "json");
});
POST.PHP
<?php
if($_POST){
if ($_POST['action'] == 'post_message') {
$fname = htmlspecialchars($_POST['FirstName']);
$lname = htmlspecialchars($_POST['LastName']);
$email = htmlspecialchars($_POST['email']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
$date = date('F j, Y, g:i a');
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($message) ) {
fail('Please select a message.');
}
if( empty($email)) {
fail('Please enter an email');
}
$query = "INSERT INTO portmessage SET first_name='$fname', last_name='$lname', email = '$email', website = '$website', message = '$message', date = '$date'";
$result = db_connection($query);
if ($result) {
$msg = "Yer message was sent.";
success($msg);
} else {
fail('Message failed, Please try again.');
}
exit;
}
}
function db_connection($query) {
mysql_connect('127.0.0.1', '######', '####')
OR die(fail('Could not connect to database.'));
mysql_select_db('####');
return mysql_query($query);
}
function fail($message) {
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
And yes, it DOES submit the form to the database, but I can't overcome the alert and redirecting problem.
Thanks, again!
You can validate your form client side(using javascript)
HTML
<form action='post.php' id='post_message' name='post_message' method="post" onsubmit="return validate_form();">
Javascript
function validate_form()
{
var success = true;
if($("[name=FirstName]").val() == "")
{
success = false;
}
// your test case goes here
// you can alert here if you find any error
return success;
}
I have an upload field in my form.
I had this code in my form.php
<form id="photoform" name="photoform" method="post" onSubmit="return false" enctype="multipart/form-data">
<div id="upphotosection"></div>
<label>Upload photo</label>
<input name="uploadphoto" id="uploadphoto" type="file" />
<div class="innerformclear"></div>
<input id="hidden" value="" name="hidden" type="hidden" />
<label> </label>
<input name="upphoto_submit" id="upphoto_submit" type="submit" value="Submit"/>
<div style="clear:both;"> </div>
<label> </label>
<div id="result_upphoto_submit"></div>
</form>
This is the code in formaction.php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
include("../../../wp-load.php");
session_start();
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if($upphoto = $_FILES['uploadphoto']["name"] != '' ){
$path = 'images/profilephotos/';
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}
$postid = 52;
############### Check Duplication
$sel_photo = "SELECT * FROM `pro_table` WHERE `post_id` = '".$postid."'";
$sel_res = mysql_query($sel_photo) ;
if(mysql_num_rows($sel_res) == 0){
$ins_photo = "Insert into pro_table (post_id,photo_photo,int_status) values ('$postid','$upphoto','0')";
$ins_res = mysql_query($ins_photo);
}
else{
$upd_photo = "Update pro_table set photo_photo = '$upphoto' ,int_status='0' where post_id = '$postid' ";
$upd_res = mysql_query($upd_photo);
}
echo $_GET['callback'] . '('.json_encode("success").')';
This is the code in java script file.
$(document).ready(function() {
///////////// Submit action for upload photo
$("#upphoto_submit").click(function() {
if(document.getElementById('uploadphoto').value == '' ){
alert("Please upload Photo");
document.getElementById('uploadphoto').focus();
return false;
}
else {
$('#result_upphoto_submit').html('<img src="http://www.test.com/test/uploads/2012/04/ajax-loader.gif" class="loader" align="absmiddle" /> ').fadeIn();
var input_data = $('#photoform').serialize();
$.ajax({
type: "POST",
url: "http://www.test.com/test/themes/test/formaction.php",
dataType: 'jsonp',
data: input_data,
success: function(msg){
$('#result_upphoto_submit').html(' ');
if(msg == 'success') {
msg = '<p class="success_custom">Photo successfully added.</p>';
$('<div>').html(msg).appendTo('div#upphotosection').hide().fadeIn('slow');
} else {
msg = ' Exists';
alert("Error in updation");
}
}
});
return false;
}
});
});
If i browse an image and click submit it showed me the success message Photo successfully added. But there is no image in profile photos folder and there is no data stored in admin panel. I couldn't track the error. How do i correct that?
is there an error in?
$_FILES["uploadphoto"]["error"];
also i dont know how wordpress handle images but i miss the file movement:
if ($_FILES["uploadphoto"]["error"] != UPLOAD_ERR_OK) {
$tmp_name = $_FILES["uploadphoto"]["tmp_name"];
$name = $_FILES["pictures"]["name"];
$path = "images/profilephotos/".$name;
move_uploaded_file($tmp_name,$path);
}
or i suppose it is called here?
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}