Redirect after clicking submit [duplicate] - javascript

This question already has answers here:
PHP Redirect to another page after form submit
(6 answers)
Closed 8 years ago.
So after I used the new JavaScript. Here is all of the code. Just keep in mind their is still top body missing. Didn't put that in as it might not be relevant to my problem.
<?php
// define variables and set to empty values
$nameErr = $surnameErr = $emailErr = $contact_numberErr = "";
$name = $surname = $email = $comment = $contact_number = "";
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["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["contact number"])) {
$contact_numberErr = "Please provide contact details";
} else {
$contact_number = test_input($_POST["contact number"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contact_number)) {
$contact_number = "Only numbers allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container" align="center">
<div class="row featured-boxes login">
<div class="col-md-6">
<div class="featured-box featured-box-secundary default info-content">
<div class="box-content">
<h4 align="center">Customer Feedback</h4>
<p><span class="error">* required field.</span></p>
<form method="post" action="insert_customer_feedback.php" name="customer_feedback">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Name</label> *<?php echo $nameErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtName" name="txtName">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Surname</label> *<?php echo $surnameErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtSurname" name="txtSurname">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>E-mail</label> *<?php echo $emailErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtEMail" name="txtEmail">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Contact Number</label> *<?php echo $contact_numberErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtContact_number" name="txtContact_number">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Comment</label>
<input type="text" value="" class="form-control input-lg" id="txtComment" name="txtComment">
</div>
</div>
<input type="button" value="Submit" class="btn btn-primary pull-right push-bottom" onClick="Confirm(this.form)">
</div>
</div>
</form>
<script type="text/javascript">
function Confirm(form){
alert("Thank you for your feedback.");
form.submit();
window.location.href = "/index.php";
}
</script>
For some reason it does not want to load my data into MySQL when having this peace of JavaScript (window.location.href = "/index.php";) added.

you can simply do it using
function Confirm(form){alert("Thank you for your feedback.");form.submit();
window.location = "location";
}

If you want to do the redirect in JavaScript it would be:
window.location.replace("yourwebsite.com/index.php");
If you wanted to do it in PHP, then it would be:
header('Location:index.php');

When you do the form.submit() you tell the form to perform the action which is stated in the forms action attribute. Thus it will automatically be redirected to whatever is set there.
Example:
<form action="submit.php" method="POST">
You code will redirect the user to the submit.php after he dismisses the alert message. When redirected to the submit.php you will have to handle a redirect from there on.
This is of course unless you are using AJAX to post the form or something like that.
Then you can just add:
window.location.href = "/index.html";
Although, in that case, it would better be placed in the success-function of the AJAX call:
function Confirm(form){alert("Thank you for your feedback.");form.submit(); window.location.href = "/index.html";}

Related

Undefined data in the email of my contact form

I should solve a problem with a contact form and I don't know where to put my hands anymore.
I have a form in HTML, then a validation in JS and finally an email sending in PHP.
The form data are: Name, Clinic, Email, Phone, Address and Valutation.
In the email I receive the data are:
Name: name entered in the form
Email: email entered in the form
Clinic: undefined
Phone: undefined
Address: undefined
Valutation: undefined
This is the code (HTML + JS):
// JavaScript Document
$(document).ready(function() {
"use strict";
$(".contact-form").submit(function(e) {
e.preventDefault();
var name = $(".name");
var email = $(".email");
var clinic = $(".clinic");
var phone = $(".phone");
var address = $(".address");
var valutation = $(".valutation");
var subject = $(".subject");
var msg = $(".message");
var flag = false;
if (name.val() == "") {
name.closest(".form-control").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".form-control").removeClass("error").addClass("success");
}
if (email.val() == "") {
email.closest(".form-control").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".form-control").removeClass("error").addClass("success");
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&subject=" + subject.val() + "&msg=" + msg.val() + "&clinic=" + clinic.val() + "&phone=" + phone.val() + "&address=" + address.val() + "&valutation=" + valutation.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "php/contactForm.php",
cache: false,
success: function(d) {
$(".form-control").removeClass("success");
if (d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="#48af4b">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="#ff5607">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").on('click', function() {
$(".form-control").removeClass("success").removeClass("error");
});
})
<div class="row justify-content-center">
<div class="col-lg-10 col-xl-8">
<div class="form-holder">
<form class="row contact-form" method="POST" action="php/contactForm.php" id="contactForm">
<!-- Form Select -->
<div class="col-md-12 input-subject">
<p class="p-lg">This question is about: </p>
<span>How satisfied are you with the service that Lab offers? </span>
<select class="form-select subject" aria-label="Default select example" name="valutation">
<option>Very unsatisfied</option>
<option>Unsatisfied</option>
<option>Satisfied</option>
<option>Very satisfied</option>
<option selected>I don't have an opinion</option>
</select>
</div>
<!-- Contact Form Input -->
<div class="col-md-12">
<p class="p-lg">Your Name: </p>
<span>Please enter your Dentist Name: </span>
<input type="text" name="name" class="form-control name" placeholder="Your Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Clinic Name: </p>
<span>Please enter your Clinic Name: </span>
<input type="text" name="clinic" class="form-control name" placeholder="Clinic Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Your Email Address: </p>
<span>Please carefully check your email address for accuracy</span>
<input type="text" name="email" class="form-control email" placeholder="Email Address*">
</div>
<div class="col-md-12">
<p class="p-lg">Phone Number: </p>
<span>Please enter your/clinic phone number: </span>
<input type="text" name="phone" class="form-control name" placeholder="Phone Number*">
</div>
<div class="col-md-12">
<p class="p-lg">Address: </p>
<span>Please enter Clinic Address: </span>
<input type="text" name="address" class="form-control name" placeholder="Address*">
</div>
<!-- Contact Form Button -->
<div class="col-md-12 mt-15 form-btn text-right">
<button type="submit" class="btn btn-skyblue tra-grey-hover submit">Submit Request</button>
</div>
<!-- Contact Form Message -->
<div class="col-lg-12 contact-form-msg">
<span class="loading"></span>
</div>
</form>
</div>
</div>
</div>
And this is the PHP code:
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$clinic = $_REQUEST["clinic"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$valutation = $_REQUEST["valutation"];
$to = "myemail#email.com";
if (isset($email) && isset($name)) {
$email_subject = "Request to access to the Price List";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: $name<br/> Email: $email <br/> Clinic: $clinic <br/> Phone: $phone <br/> Address: $address <br/> Valutation: $valutation";
$mail = mail($to, $email_subject, $msg, $headers);
if ($mail) {
echo 'success';
} else {
echo 'failed';
}
}
?>
Your issue is your selectors. You only use classes name and email for all your inputs.
<input type="text" name="phone" class="form-control name" ...>
should actually be:
<input type="text" name="phone" class="form-control phone" ...>
and so on for all the other inputs. Change your selectors to the appropriate classNames.
Also, never just use i.e: $(".name");, $(".email"); etc. as your selectors. As you know already $(".name"); will get every class="name" in your document. Same goes for all the other selectors. Instead, use the second argument (ParentElement) that will limit the search only to the children elements of the provided parent:
var name = $(".name", this);
or rather, use attribute selectors like:
var clinic = $(`[name="clinic"]`, this);
IMPORTANT NOTE about validation:
never trust the client.
JS validation should be used minimally, just as a UX tool to help, inform the user about basic errors/typos. The real validation, as well as all the related error responses, should be handled on the backend side.
Currently your PHP seems quite open to XSS attacks.
You don't need a HTML <form> in order to send data to the server. All it takes to an attacker is to find your route/path (usually exposed via the form's action attribute), take a look at the names in the source and manually construct a HTTP request, and send dangerous arbitrary data to your server. Just so you keep in mind.

theme php contact form

I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});

Registration/Login Confirmation Before Redirect

I have a registration and login form which is working and updates/queries the database linked to my website. Currently, I am using JavaScript for client side validation before executing the registration/login processes on the server side (also has validation but only to make sure fields that are posted from the forms are not empty). Once these processes are done, the user is redirected to home/redirect page. However, for a better Human-Computer Interaction, I wish for the web page to show a loading icon while the server side deals with the registration/login processes and then display a confirmation message to the user if the details are correct before redirecting them to the home/redirect page. Is there any way I can achieve this? Any suggestions/help would be appreciated.
Registration Form
<form method="POST" action="userRegistration.php" id="registrationForm" novalidate>
<div class="form-row">
<div class="col-md-6 pt-4">
<div class="form-group">
<input type="text" class="form-control" id="firstname" name="firstname" required />
<label class="form-ph" for="firstname" id="firstnamePlaceholder">FIRST NAME</label>
</div>
</div>
<div class="col-md-6 pt-4">
<div class="form-group">
<input type="text" class="form-control" id="surname" name="surname" required />
<label class="form-ph" for="surname" id="surnamePlaceholder">LAST NAME</label>
</div>
</div>
</div>
<div class="form-row">
<div class="col pt-4">
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" autocomplete="off" required />
<label class="form-ph" for="email" id="emailPlaceholder">EMAIL ADDRESS</label>
<small>
<span id="emailCheck"></span>
</small>
</div>
</div>
</div>
<div class="form-row">
<div class="col pt-4">
<div class="form-group">
<input type="text" class="form-control" id="usernameSignup" name="usernameSignup" autocomplete="off" minlength="6" maxlength="32" required />
<label class="form-ph" for="usernameSignup" id="usernameSignupPlaceholder">USERNAME</label>
<small id="helpBlock" class="form-text text-muted">
Must be between 6-32 characters
<span id="usernameCheck"></span>
</small>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6 pt-4">
<div class="form-group">
<input type="password" class="form-control" id="passwordSignup" name="passwordSignup" minlength="8" required />
<label class="form-ph" for="passwordSignup" id="passwordSignupPlaceholder">PASSWORD</label>
<small id="helpBlock" class="form-text text-muted">
Must be 8 or more characters
</small>
</div>
</div>
<div class="col-md-6 pt-4">
<div class="form-group">
<input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm" required />
<label class="form-ph" for="passwordConfirm" id="passwordConfirmPlaceholder">CONFIRM PASSWORD</label>
<small>
<span id="passwordCheck"></span>
</small>
</div>
</div>
</div>
<p>
By creating an account, you agree to our Terms and Conditions &
Privacy Policy.
</p>
<button type="submit" class="btn btn-primary btn-block" id="registrationButton">
SIGN UP
</button>
</form>
Registration Server Side Process
<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
require_once("dbConn.php");
$dbConn = getConnection();
} catch (Exception $e) {
echo "A problem occured: " . $e->getMessage();
}
// Form validation for POST method to check fields are not empty
if (!empty($_POST['firstname'])) {
$firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
$firstname = trim($firstname);
} else {
echo "A first name must be entered.<br/>";
}
if (!empty($_POST['surname'])) {
$surname = filter_has_var(INPUT_POST, 'surname') ? $_POST['surname'] : null;
$surname = trim($surname);
} else {
echo "A surname must be entered.<br/>";
}
if (!empty($_POST['email'])) {
$email = filter_has_var(INPUT_POST, 'email') ? $_POST['email'] : null;
$email = trim($email);
} else {
echo "An email address must be entered.<br/>";
}
if (!empty($_POST['usernameSignup'])) {
$usernameSignup = filter_has_var(INPUT_POST, 'usernameSignup') ? $_POST['usernameSignup'] : null;
$usernameSignup = trim($usernameSignup);
} else {
echo "A username must be entered.<br/>";
}
if (!empty($_POST['passwordSignup'])) {
$passwordSignup = filter_has_var(INPUT_POST, 'passwordSignup') ? $_POST['passwordSignup'] : null;
$passwordSignup = trim($passwordSignup);
} else {
echo "A password must be entered.<br/>";
}
if (!empty($_POST['passwordConfirm'])) {
$passwordConfirm = filter_has_var(INPUT_POST, 'passwordConfirm') ? $_POST['passwordConfirm'] : null;
$passwordConfirm = trim($passwordConfirm);
} else {
echo "A password must be entered that matches the previous one.<br/>";
}
// Checks to see if both passwords entered match, to set the passwordHash variable.
if ($passwordSignup == $passwordConfirm) {
$passwordHash = password_hash($passwordSignup, PASSWORD_DEFAULT);
} else {
echo "The passwords entered don't match, please try again <br/>";
}
// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
try {
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
$dbConn->exec($sqlQuery);
header("location: index.php");
exit;
} catch (PDOException $e) {
echo $sqlQuery . "<br>" . $e->getMessage();
}
}
JavaScript Validation
$("#registrationForm").submit(function(event) {
$("#registrationForm input").each(function() {
if (!$(this).hasClass("is-valid")) {
$(this).addClass("is-invalid");
event.preventDefault();
event.stopPropagation();
}
});
});
Login Form
<form method="POST" action="userAuthentication.php" id="loginForm" novalidate>
<div class="form-row">
<div class="col-12 pt-4">
<div class="form-group">
<input type="text" class="form-control" id="username" name="username" required />
<label class="form-ph" for="username" id="usernamePlaceholder">USERNAME</label>
</div>
</div>
</div>
<div class="form-row pb-3">
<div class="col-12 pt-3">
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" required />
<label class="form-ph" for="password" id="passwordPlaceholder">
PASSWORD
</label>
<small id="helpBlock" class="float-right">
Forgotten Password?
</small>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block" id="loginButton">
SIGN IN
</button>
</form>
Login Server Side Process
<?php
// try catch statement to connect to the database connection file to use the getConnection() function and store it
// in $dbConn. If it doesn't connect, then show the error message.
try {
ini_set("session.save_path", "/home/unn_w16010421/sessionData");
session_start();
require_once("dbConn.php");
$dbConn = getConnection();
} catch (Exception $e) {
// Instead of echoing error, redirect user to error page for a more professional look.
echo "A problem occured: " . $e->getMessage();
}
// Takes the entered username and password from the post method (Login form) and stores them into a variable for
// later use.
$username = filter_has_var(INPUT_POST, 'username') ? $_POST['username'] : null;
$username = trim($username);
$password = filter_has_var(INPUT_POST, 'password') ? $_POST['password'] : null;
// If the post method has an empty username or password let the user know.
if (empty($username) || empty($password)) {
// Again in stead of echoing error, redirect user to error page for a more professional look.
echo "You need to provide a username and a password. Please try again.";
}
// Else, check the database for a match with the inputted username and password.
else {
// try statement to check if the entered username and password matches with one in the database.
try {
// Clears any session data.
// $_SESSION = array();
// SQL Query to retrieve the passwordHash for a user from the GH_users table where the username entered by
// the user matches one in the database.
$sqlQuery = "SELECT passwordHash FROM GH_users WHERE username = :username";
$stmt = $dbConn->prepare($sqlQuery);
// Executes the query to go through the array until the username entered by the user matches one in the
// database and stores it into $user variable.
$stmt->execute(array(':username' => $username));
$user = $stmt->fetchObject();
// If the query returns a user with the entered username, then check if the password entered also matches
// with the one in the database. If it does, authentication is complete and create a session for the user.
// Redirect user to home page.
if ($user) {
if (password_verify($password, $user->passwordHash)) {
$userID = $user->userID;
$_SESSION['userID'] = $userID;
$_SESSION['logged-in'] = true;
$_SESSION['username'] = $username;
if (isset($_SESSION['login_redirect'])) {
header("Location: " . $_SESSION['login_redirect']);
// Cleans up the session variable
unset($_SESSION['login_redirect']);
exit;
} else {
header("location: index.php");
exit;
}
}
// If the password for an existing username doesn't match with the one in the database, inform the user
else {
echo "The username and/or password was incorrect, please try again.";
}
}
// If the query doesn't return a user, inform the user.
else {
echo "The username or password was incorrect, please try again.";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
Since you're using jQuery you can use the following functions to run an animation during an AJAX call which would perform the submission of the form:
$(document).ajaxStart(function(){
// code to display animation
});
$(document).ajaxStop(function(){
// code to remove animation when AJAX is complete
});
Your redirection should be in the AJAX return, not the PHP code.

Codeigniter upload image file with array field name

I'm quite new to the codeigniter library and function. Recently i had a form that had a few dynamic input field to be submit and insert into database for recording purpose.
The image upload file field was dynamically created if user click "+" button, and i was using array name as the name for the input field. However when i trying to call the controller to upload the file or insert with the array field name, it keep prompted me 'You did not select a file to upload'.
If i change the image field's input name to only 'reg_photo' and the do upload field name to 'reg_photo' then everything working fine but that is not i wanted because i wanted to upload it based on the dynamic input array.
I did try to look around the solution at stackoverflow and google but after i try and none of it could help me.
Here are my Controller to do the upload :
//Upload Picture Configuration
$config['upload_path'] = './uploads/profile_picture/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1920;
$config['max_height'] = 1080;
$this->load->library('upload', $config);
//Check and get the Areas list
$areaList = $this->input->post('areas', true);
$finalSeparator = $areaList;
$resultArea = "";
foreach ($finalSeparator as $i => $a) {
if (next($finalSeparator )) {
$resultArea .= $a.','; // Add comma for all elements instead of last
}
else
{
$resultArea .= $a;
}
}
if ($this->input->post('reg_name')) { // returns false if no property
//Get Last Inserted District ID
$district = "";
$failedUploadNameList = "";
$photoPath = "";
$data = array(
'district_code' => $this->input->post('reg_district_2', true),
'district_country' => '',
);
$this->db->set('district_registered_date', 'NOW()', FALSE); //Submit current date time
if($this->Registerlanguage_admin_model->register_district($data))
{
$district = $this->db->insert_id(); //Last Get ID
$name = $this->input->post('reg_name', true);
$year1 = $this->input->post('reg_year1', true);
$year2 = $this->input->post('reg_year2', true);
$nickname = $this->input->post('reg_nickname', true);
$photo = $this->input->post('reg_photo', true);
foreach ($name as $i => $a) { // need index to match other properties
//Check to whether can upload image or not
if ( ! $this->upload->do_upload($photo[$i]))
{
$error = array('error' => $this->upload->display_errors());
foreach($error as $q)
{
$failedUploadNameList .= $q;
}
}
else
{
$data = array('upload_data' => $this->upload->data('file_name'));
foreach($data as $a)
{
$photoPath = $config['upload_path'].$a;
}
}
$data = array(
'area_district_id' => $district,
'area_name' => $resultArea,
'area_language' => $this->input->post('reg_language', true),
'area_year_1' => isset($year1[$i]) ? $year1[$i] : '',
'area_year_2' => isset($year2[$i]) ? $year2[$i] : '',
'area_leader_name' => isset($name[$i]) ? $name[$i] : '',
'area_leader_nickname' => isset($nickname[$i]) ? $nickname[$i] : '',
'area_leader_photo' => $photoPath
);
$this->db->set('area_registered_date', 'NOW()', FALSE); //Submit current date time
if (!$this->Registerlanguage_admin_model->register_area($data)) {
// quit if insert fails - adjust accordingly
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
}
}
else{
// don't redirect inside the loop
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
//Redirect back once all successfully insert
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Insert Successfully!</div>'.$failedUploadNameList);
redirect('index.php/language_admin/index');
}
else{
// don't redirect inside the loop
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
Here are my view code :
<?php $attributes = array("name" => "registerdistrictform");
echo form_open_multipart("index.php/registerlanguage_admin/registerDistrict", $attributes);?>
<div class="panel panel-default">
<div class="panel panel-info">
<div class="panel-body panel-group">
<div class="form-group">
<input class="form-control" name="reg_language" type="hidden" value="Japanese" />
<label for="concept" class="col-sm-3 control-label">District :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_district_1" placeholder="Ex : District 3500" type="text" value="<?php echo set_value('reg_district_1'); ?>" required/>
<span class="text-danger"><?php echo form_error('reg_district_1'); ?></span><br/>
<input class="form-control" name="reg_district_2" placeholder="Ex : 3500" type="text" value="<?php echo set_value('reg_district_2'); ?>" required/>
<span class="text-danger"><?php echo form_error('reg_district_2'); ?></span><br/>
</div>
</div>
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Area :</label>
<div id="areaContainer">
<div class="col-sm-6">
Area Record #0<input class="form-control" name="areas[]" placeholder="Your Language" type="text" value="" required/>
</div>
<div class="col-sm-3">
+<br/>
</div>
</div>
</div>
</div>
</div>
<div id = "profileContainer">
<div class="panel panel-danger">
<div class="panel-heading">Profile #0</div>
<div class="panel-body panel-group">
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Years :</label>
<div class="col-sm-4">
<input class="form-control" name="reg_year1[]" placeholder="2015" type="text" value="" required/>
</div>
<div class="col-sm-1">
<i class="fa fa-arrow-right" aria-hidden="true" ></i>
</div>
<div class="col-sm-4">
<input class="form-control" name="reg_year2[]" placeholder="2017" type="text" value="" required/><br/>
</div>
</div>
<div class="form-group">
<label for="concept" class="col-sm-12 control-label"><u>District Governer</u></label><br/>
<label for="concept" class="col-sm-3 control-label">Name :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_name[]" placeholder="Your Language" type="text" required/><br/>
</div>
<label for="concept" class="col-sm-3 control-label">Nickname :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_nickname[]" placeholder="English" type="text" required/><br/>
</div>
<label for="concept" class="col-sm-3 control-label">Photo :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_photo[]" type="file" required/><br/>
</div>
</div>
<div class="pull-right">
+
</div>
</div>
</div>
</div>
<div class="panel-body panel-group">
<div class="form-group">
<div class="col-sm-1 text-left">
<button name="submit" type="submit" class="btn btn-info btn-lg" >Submit</button>
<!-- <button name="cancel" type="reset" class="btn btn-info">Cancel</button>-->
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
</div>
The 'reg_photo[]' are dynamically insert into HTML if user press the '+' button, so if i change to 'reg_photo' which is not dynamic anymore then it work, what should i do if i wanted to use the 'reg_photo[]' as a field name to upload my file? Please guide me through this. Thank! :)
/*
* Code above omitted purposely
* In your HTML form, your input[type=file] must be named *upl_files[]*
*/
/*
* Uploads multiple files creating a queue to fake multiple upload calls to
* $_FILE
*/
public function multiple_upload()
{
$this->load->library('upload');
$number_of_files_uploaded = count($_FILES['upl_files']['name']);
// Faking upload calls to $_FILE
for ($i = 0; $i < $number_of_files_uploaded; $i++){
$_FILES['userfile']['name'] = $_FILES['upl_files']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['upl_files']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['upl_files']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['upl_files']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['upl_files']['size'][$i];
$config = array(
'file_name' => <your ouw function to generate random names>,
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => 3000,
'overwrite' => FALSE,
/* real path to upload folder ALWAYS */
'upload_path'
=> $_SERVER['DOCUMENT_ROOT'] . '/path/to/upload/folder'
);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}else {
$final_files_data[] = $this->upload->data();
// Continue processing the uploaded data
}
}
}
This Worked for me. reffer to this page this is not my code
https://gist.github.com/zitoloco/1558423
Try this code to upload image
$directory = "./images/";
$config['upload_path'] = $directory;
$config['encrypt_name'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
if (!$this->upload->do_upload('mainimage'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else {
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
And one other change is :
Replace upload.php file.
take latest verison upload.php file from system directory -> libraries directory -> upload.php. Copy new version upload.php file and replace in your project
Hope it will work properly.

Form submission success message not displaying

I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}

Categories