Codeigniter jquery ajax: post data to controller issues - javascript

I'm working on login system in codeigniter 3.0 and jquery ajax. I want to post data to controller using ajax and return a value if the data thrown by ajax is match from the mysql database. I also try those suggestion/s from this existing post but i think its not working. I don't want to rely the redirect from codeigniter.
MAIN PROBLEM: i want to check if the username and password data are incorrect, it prompts an error with no page refresh. But i did was throw an boolean value from controller to view for projecting an error-like html tag.
heres the code:
readyLogin.js
var ReadyLogin = function () {
return {
init: function () {
/*
* Jquery Validation, Check out more examples and documentation at https://github.com/jzaefferer/jquery-validation
*/
/* Login form - Initialize Validation */
$('#form-login').validate({
errorClass: 'help-block shake animated', // You can change the animation class for a different entrance animation - check animations page
errorElement: 'div',
errorPlacement: function (error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function (e) {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
},
rules: {
'login-username': {
required: true
},
'login-password': {
required: true,
minlength: 5
}
},
messages: {
'login-username': {
required: "Please enter Administrator's username."
},
'login-password': {
required: "Please provide Administrator's password.",
minlength: 'Your password must be at least 5 characters long.'
}
}
});
$("#form-login").submit(function(){
$.ajax({
type: "POST",
url: $('#form-login').attr('action'),
data: {"login-username": $("#login-username").val(), "login-password": $("#login-password").val()},
dataType: "json",
success: function (returnData) {
alert(data); // to check if there's a thrown data from the view to controller
// below is a "trial" code that checks the status if the controller receives data from ajax
if (returnData.status == true) {
console.log(returnData.status);
} else {
console.log('empty');
}
}
});
});
}
};
}();
controller/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
}
public function index() {
$data['error'] = false;
$result = $data['error'];
if ($_POST) {
$this->load->model('Login_model');
$username = $this->input->post('login-username', true);
$password = $this->input->post('login-password', true);
$user = $this->Login_model->login($username, $password);
if (!$user && $user == null) {
$data['error'] = true; //throwing boolean value to make error html tag
$result = array('status' => true);
json_encode($result);
} else {
$data['error'] = false;
$this->session->set_userdata('username', $user['usename']);
$this->session->set_userdata('password', $user['password']);
redirect(base_url() . 'Maps');
}
}
$this->load->view('Backend/page_ready_login', $data);
}
function logout() {
$this->session->sess_destroy();
redirect(base_url(), 'refresh');
}
}
model/Login.php
<?php
class Login_model extends CI_Model {
function login($username,$password){
$where=array(
'username'=>$username,
'password'=>sha1($password)
);
$this->db->select()->from('admin')->where($where);
$query=$this->db->get();
return $query->first_row('array');
}
}
views/Backend/page_ready_login.php
<?php
include 'assets/Backend/inc/config.php';
$template['title'] = 'BCGIS | LOGIN';
$template['page_preloader'] = true;
?>
<?php include 'assets/Backend/inc/template_start.php'; ?>
<!-- Login Container -->
<div id="login-container">
<!-- Login Header -->
<h1 class="h3 text-light text-center push-top-bottom fadeIn animated">
<div class="row">
<div class="col-lg-3 fadeIn animated">
<img src="<?= base_url(); ? >assets/Backend/images/Ph_seal_davao_del_norte_panabo_city.png" style="width: 95px; height: 80px;"/>
</div>
<div class="col-lg-9 fadeIn animated">
<strong>Brgy. Cagangohan Geographical Information System</strong>
</div>
</div>
</h1>
<!-- END Login Header -->
<!-- Login Block -->
<div class="block fadeIn animated">
<!-- Login Title -->
<div class="block-title">
<h2>Administration Login</h2>
</div>
<!-- END Login Title -->
<!-- Login Form -->
<form id="form-login" action="<?= base_url(); ?>" method="post" class="form-horizontal">
<?php if ($error == true) { ?>
<h5 class="alert alert-danger shake animated" id="login-error">Your Username/Password is incorrect!</h5>
<?php } ?>
<div class="form-group">
<div class="col-xs-12">
<input type="text" id="login-username" name="login-username" class="form-control" placeholder="Username..">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input type="password" id="login-password" name="login-password" class="form-control" placeholder="Password..">
</div>
</div>
<div class="form-group form-actions">
<div class="col-sm-offset-2 col-sm-8 text-center">
<center>
<button type="submit" id="login-button" name="login-button" class="btn btn-effect-ripple btn-block btn-primary"><i class="fa fa-check"></i> Sign In</button>
</center>
</div>
</div>
</form>
<!-- END Login Form -->
</div>
<!-- END Login Block -->
<!-- Footer -->
<footer class="text-muted text-center fadeIn animated">
<small><span id="year-copy"></span> © <?php echo $template['name'] . ' ' . $template['version']; ?></small>
</footer>
<!-- END Footer -->
</div>
<!-- END Login Container -->
<?php include 'assets/Backend/inc/template_scripts.php'; ?>
<!-- Load and execute javascript code used only in this page -->
<script src="<?= base_url(); ?>assets/Backend/js/pages/readyLogin.js"> </script>
<script>
$(function () {
ReadyLogin.init();
});
</script>
<?php include 'assets/Backend/inc/template_end.php'; ?>
Any suggestion/s and help fixing this is much appreciated. Thanks.

In your controller method, change this:
if (!$user && $user == null) {
To this:
if (!$user || $user == null) {

Related

Retrieving data from a form (Codeigniter, AJAX)

I have a problem with a form.
I need to do a login form, but I can't retrieve login data.
This is my view login.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="main">
<div class="container">
<div class="card card-container">
<h1>Control de Asistencia</h1>
<form id="login" class="form-signin" method="post" action="<?php echo
base_url('login/ingresar'); ?>">
<span id="reauth-email" class="reauth-email"></span>
<input type="email" name="email" id="inputEmail" class="form-control"
placeholder="Usuario" required autofocus>
<input type="password" name="password" id="inputPassword" class="form-control"
placeholder="Clave" required>
<br/>
<button class="center btn btn-raised btn-info btn-lg" type="submit">Ingresar</button>
<div class="login__rpta"></div>
</form><!-- /form -->
</div><!-- /card-container -->
</div><!-- /container -->
</div><!--main-->
The controller Login.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('Login_model');
}
function ingresar(){
$email = $this->input->post("email");
$password= md5($this->input->post("password"));
$resp = $this->Login_model->login($email, $password);
if($resp){
$data = [
"id" => $resp->id,
"name" => $resp->nombre,
"nivel" => $resp->nivel,
"login" => TRUE
];
$this->session->set_userdata($data);
}
else{
echo "errorxxx";
}
}
function cerrar(){
$this->session->sess_destroy();
redirect(site_url());
}
}
Javascript custom.js:
$(function () {
$.material.init();
$("#login").submit(function(event){
event.preventDefault();
$.ajax({
url:$(this).attr("action"),
type:$(this).attr("method"),
data:$(this).serialize(),
success:function(resp){
if(resp==="error"){
$('.login__rpta').html("Usuario o clave incorrectos");
console.log(resp);
}
else{
window.location.href = base_url + "welcome/home";
console.log(resp);
}
}
});
});
------ more code ------
});
EDITED: this is the model Login_model.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Login_model extends CI_Model {
function login($email, $password){
$this->load->database();
$this->load->dbutil();
// check connection details
if( !$this->dbutil->database_exists('myDatabase')) {
echo 'Not connected to a database, or database not exists';
} else {
echo 'Conectado';
}
$this->db->where("email", $email);
$this->db->where("password", $password);
$resultados = $this->db->get("profesores");
if ($resultados->num_rows()>0) {
return $resultados->row();
}
else{
return false;
}
}
}
The console.log from custom.js show me the view (the form) instead of the login parameters, and it redirects me to a 404 error page... What am I doing wrong, please?
This is not my code (I'm just trying to fix it) and I can't see the problem!
Your base_url is defined in codeigniter's config.php, for example like:
$config['base_url'] = 'http://or.org/';
That doesn't mean you can simply use base_url as a variable in javascript hoping to get that value.
But you can echo it out like:
window.location.href = '<?php echo base_url()?>' + 'welcome/home'
or just use the relative path
window.location.href = '/welcome/home'

Show modal on page load after login success

Login form (seperate file):
<div class="" id="login-form">
<img class="Lpic" src="img/loginpic.png">
<div class="fieldtext">
<h2 class="text-center">Login</h2>
</div>
<div>
<?php
if($_POST)
{
//form validation
if(empty($_POST['Email']) || empty($_POST['Password']))
{
$errors[] = 'Please enter email and password';
}
//check if email exists
$query = $db->query("SELECT * FROM users WHERE Email = '$email'");
$user = mysqli_fetch_assoc($query);
$userCount = mysqli_num_rows($query);
if($userCount < 1)
{
$errors[] = 'Unknown email, pleas verify';
}
if(password_verify($password, $user['Password']))
{
$errors[] = 'Password doesn\'t match, try again';
}
if(!empty($errors))
{
echo display_errors($errors);
}else{
//log user in
$user_id = $user['ID'];
login($user_id);
}
}
?>
</div>
<form action="Login.php" method="post">
<div class="inputfield">
<div class="form-group">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" value="<?=$email;?>">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" id="Password" value="<?=$password;?>">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-success btn-block">
Cancel
</div>
</form>
</div>
functions used in login form:
function login($user_id)
{
$_SESSION['OpenWorld'] = $user_id;
global $db;
$date = date("Y-m-d H:i:s");
$db->query("UPDATE users SET Last_Login = '$date' WHERE ID = '$user_id'");
$_SESSION['success_flash'] = "You are now logged in";
header('Location: ../shop/Mainshop.php');
}
function display_errors($errors)
{
$display = '<ul class="bg-danger danger-pos">';
foreach($errors as $error)
{
$display .= '<li class="text-danger">'.$error.'</li>';
}
$display .='</ul>';
return $display;
}
if(isset($_SESSION['success_flash']))
{
echo '<div class="bg-success"><p class="text-success text-center">'.$_SESSION['success_flash'].'</p></div>';
unset($_SESSION['success_flash']);
}
instead of the message "You are now logged in" i want this modal to pop up which disappears after x seconds
modal: (seperate file)
<div class="welcome-modal modal-bg" id="welcome-modal">
<div class="welcome-text">
<div class="message-bg">
<p class="message-text">Welcome <?=$user_data['First'];?></p>;
</div>
</div>
<div class="G-image">
<img src="../../global-img/welcome.png">
</div>
</div>
i tried this javascript (on the page where the user will be headed after logging in)
$(document).ready(function (){
$.ajax({
url : '/Cybernetics/Admin/Login.php',
method : "post",
success : function(){
$(window).on('load', function(){
$('#welcome-modal').modal('show');
})
}
});
});
i don't really know what im doing here lmao, i don't really know much about javascript and new to php...........
PS: bootstrap js is included...TIA
No need to use $(window).on('load', function() on the ajax success.
You can immediately just show the modal after ajax was succesful and set a timeout for it to disappear after x milliseconds
success : function(){
$('#welcome-modal').modal('show');
setTimeout(function(){ $('#welcome-modal').modal('hide'); }, 2500);
}
Demo:
$(document).ready(function() {
$('#welcome-modal').modal('show');
setTimeout(function() {
$('#welcome-modal').modal('hide');
}, 2000);
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<div id="welcome-modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<p>Welcome User.</p>
</div>
</div>
</div>
</div>

Contact form doesn't validate inside bootstrap modal

So I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine when placed on a page, however when I place it inside a bootstrap popup modal, the validator doesn't work. If all fields are empty and submit button hit, it will say 'message sent' even though it did not send, and if you fill in the fields it will still send and give success message also.
Also, if I hit the button to open modal as soon as page loads but before the script has loaded, it will work, so it's obviously because the modal is not visible when the validator script loads, so it misses it.
If anyone has some answers it would be super helpful as I'm pretty new to PHP and JS!
Here is my modal HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_email">Email *</label> <input class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_message">Message *</label>
<textarea class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>
This is my PHP file
<?php
// configure
$from = '<mail#myemail.net>';
$sendTo = 'Demo contact form <mail#myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail#myemail.net' . "\r\n" ;
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($email, $subject2, $msg, $headers) && mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $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['message'];
}
?>
And 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();
}
}
});
return false;
}
})
});
Put your ajax call inside the validation process and use submitHandler.
This answer by #Sparky might save your day https://stackoverflow.com/a/15625824/6952155
Please refer to this and edit to suit in your code.
$(document).ready(function () {
$("#contactform").validate({
ignore: ":hidden",
rules: {
name: {
required: true,
minlength: 3
},
cognome: {
required: true,
minlength: 3
},
subject: {
required: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "formfiles/submit.php",
data: $(form).serialize(),
success: function () {
$(form).html("<div id='message'></div>");
$('#message').html("<h2>Your request is on the way!</h2>")
.append("<p>someone</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/ok.png' />");
});
}
});
return false; // required to block normal submit since you used ajax
}
});
});
Ondrej here, author of the tutorial on Bootstrapious.
I have just found out that there was an error in Bootstrap validator and it was not working correctly in combination with the Bootstrap modal.
The solution is downloading the latest version from https://github.com/1000hz/bootstrap-validator, currently 0.11.5.
Best,
Ondrej

Bootbox is not working when calling a modal form

I am using bootbox modal for calling a modal form but form is not appeared as a modal. Nothing happens when we click compose. I want to open a form in a model after clicking the compose button but its not working.
<a class="btn btn-block btn-compose btn-lg" id="loginButton"><i class="fa fa-" ></i> Compose Mail </a>
<!-- The login modal. Don't display it initially -->
<form id="loginForm" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-xs-3 control-label">To</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="to" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Subject</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="ssubject" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Message</label>
<div class="col-xs-5">
<textarea name="smessage" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</form>
This is html form and the java script file are placed in same page inbox.php
$(document).ready(function() {
$('#loginForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
to: {
validators: {
notEmpty: {
message: 'Please type destination bo'
}
}
},
ssubject: {
validators: {
notEmpty: {
message: 'Please type subject'
}
}
},
smessage: {
validators: {
notEmpty: {
message: 'Please type some message'
}
}
}
}
});
// Login button click handler
$('#loginButton').on('click', function() {
bootbox
.dialog({
title: 'Compose Message',
message: $('#loginForm'),
show: true // We will show it manually later
})
.on('shown.bs.modal', function() {
$('#loginForm')
.show() // Show the login form
.formValidation('resetForm', true); // Reset form
})
.on('hide.bs.modal', function(e) {
// Bootbox will remove the modal (including the body which contains the login form)
// after hiding the modal
// Therefor, we need to backup the form
$('#loginForm').hide().appendTo('body');
})
.modal('show');
});
});
</script>
<script>
$(document).ready(function() {
$('#loginForm').on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
validator = $form.data('formValidation'),
username = validator.getFieldElements('username').val();
// Hide the modal containing the form
$form.parents('.bootbox').modal('hide');
// Show the welcome dialog
// Use Ajax to submit form data
$.ajax({
//url: $form.attr('action'),
url: 'test/send.php',
type: 'POST',
data: $form.serialize(),
success: function(result) {
//alert(result);
//bootbox.alert('Welcome back, ' + username);
bootbox.alert(result);
window.location.reload();
}
});
});
});
</script>
and here's the test/send.php code.
<?php
$from="0";
$to=$_POST["to"];
$subject=$_POST["ssubject"];
$message=$_POST["smessage"];
//echo $to.$message;
//validate before insert
if(strlen($subject)>50){
echo "Subject was too long";
die();
}
if(strlen($message)>150){
echo "Message was too long";
die();
}
include('../dbsource.php');
$mysqli=connect();
if(insert($mysqli,$from,$to,$subject,$message)>0)
echo "Message was sent";
else
echo "Message was not sent";
?>
<?php
function insert($mysqli,$from,$to,$subject,$message){
$mdate=date('Y-m-d');
$mtime=date('H:i:s');
$query = "INSERT INTO messages (mfrom,mto,subject,message,mdate,mtime)".
"VALUES ('$from','$to','$subject','$message','$mdate','$mtime')";
if($mysqli->query($query)>0)
return($mysqli->insert_id);
else
return 0;
}
?>
The modal does not appear.
I dont know why is the modal is not appearing in this project.
Can anybody help me ?
error in console:

How to set blind input field to validate form?

im trying to set up a blind input field with php that will check and make sure the input field is empty and if it is not empty it will not send the message that it is set up to send but I've run into several problems with placement and wording of this here is my code any input would greatly be appreciated.
<?php
// Set email variables
$email_to = 'email#example.com';
$email_subject = 'Website Message';
// Set required fields
$required_fields = array('fullname','email','comment');
$fakes = array('Email1');
// set error messages
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($fakes as $fake)
if($fake == 'Email1') if(!check_for_content($_POST[$fake])) die;
else {
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
function check_for_content($fake = FALSE) {
return (preg_match('[A-Z0-9._%+-]', $Email1))? TRUE : FALSE;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Contact Form Designed by James Brand # dreamweavertutorial.co.uk -->
<!-- Covered under creative commons license - http://dreamweavertutorial.co.uk/permissions/contact-form-permissions.htm -->
<title>Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui-compressed.js"></script>
<script type="text/javascript" src="validation/validation.js"></script>
<script type="text/javascript">
var nameError = '<?php echo $error_messages['fullname']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
</head>
<body>
<div id="Contactus">
<p>Chisel Multimedia</p>
<p>275 Roswell Street NE <br />
Marietta GA 30060</p>
</div>
<br />
<div id="formWrap">
<div id="form">
<?php if($form_complete === FALSE): ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="comments_form">
<div id="label1" 865style="display:none">
<div class="row">
<div class="label">Email</div>
<!-- end .label -->
<div class="input">
<input type="text" id="Email1" class="detail" name="Emial1" />
</div>
<!-- end .input -->
<div class="context">e.g. John Smith or Jane Doe</div>
<!-- end .context-->
</div>
<!-- end .row -->
</div>
<div class="row">
<div class="label">Your Name</div>
<!-- end .label -->
<div class="input">
<input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" />
<?php if(in_array('fullname', $validation)): ?>
<span class="error"><?php echo $error_messages['fullname']; ?></span>
<?php endif; ?>
</div>
<!-- end .input -->
<div class="context">e.g. John Smith or Jane Doe</div>
<!-- end .context-->
</div>
<!-- end .row -->
<div class="row">
<div vlass="label">Your Email Address</div>
<!-- end .lable -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<?php if(in_array('email', $validation)): ?>
<span class="error"><?php echo $error_messages['email']; ?></span>
<?php endif; ?>
</div>
<!-- end .input -->
<div class="context">abc#bca.com</div>
<!-- end .context-->
</div>
<!-- end .row -->
<div class="row">
<div vlass="label">Your Message</div>
<!-- end .lable -->
<div class="input">
<textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea>
<?php if(in_array('comment', $validation)): ?>
<span class="error"><?php echo $error_messages['comment']; ?></span>
<?php endif; ?>
</div>
<!-- end .input -->
</div>
<!-- end .row -->
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send Message" />
</div>
<!-- end submit -->
</form>
<?php else: ?>
<p style="font-size: 10px; color: #255e67; width: 65%;">Thank you for your Message!</p>
<?php endif; ?>
</div>
<!-- end form -->
</div>
<!-- end formWrap -->
</body>
</html>
You have to much errors in your code, that prevents you from getting correct results
<input type="text" id="Email1" class="detail" name="Emial1" />
Pay attention, that name="Emial1", but in php code you check for 'Email1'. Correct one of those.
Next piece:
function check_for_content($fake = FALSE) {
return (preg_match('[A-Z0-9._%+-]', $Email1))? TRUE : FALSE;
}
Using $Email1 variable is just out of place. Regex expression is lack of boundaries. At least it should be
function check_for_content($fake = FALSE) {
return (preg_match('/[A-Z0-9._%+-]/i', $fake))? TRUE : FALSE;
}
And when you calling this function why Not condition?
if($fake == 'Email1') if(!check_for_content($_POST[$fake])) die();
I think it should be vice versa.
Anyway, personally I'll just use something like this:
foreach($fakes as $fake)
if(!empty($_POST[$fake])) { die();}
// dont need 'else'
Also when debugging your php code, make sure you turn on errors, it realy helps
error_reporting(0);
ini_set('display_errors', 0);

Categories