Zend form submit does not work after validation fail - only in Chrome - forms

I have a login form with three inputs - username, password and submit with validation.
If either username or password are empty then validation fails correctly.
However in Chrome I cannot resubmit the form - clicking submit has no effect.
In IE and Firefox it works fine.
Zend Controller Action:
public function loginAction()
{
$this->_helper->layout->setLayout('layout_nomenu');
$loginForm = new Application_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
$valid = false;
if ($valid) {
//if ($this->_process($loginForm->getValues())) {
$this->_helper->redirector('users', 'grid');
} else {
$this->view->loginfail = "Login details not recognised, please try again";
}
}
}
$this->view->login = $loginForm;
}
forms.ini:
[login]
action = "login"
method = "post"
name = "login"
elements.username.type = "text"
elements.username.options.label = "Username:"
elements.username.options.validators.strlen.validator = "StringLength"
elements.username.options.validators.strlen.options.min = "2"
elements.username.options.validators.strlen.breakChainOnFailure = "true"
elements.username.options.required = "true"
elements.password.type = "password"
elements.password.options.label = "Password:"
elements.password.options.validators.strlen.validator = "StringLength"
elements.password.options.validators.strlen.options.min = "2"
elements.password.options.validators.strlen.breakChainOnFailure = "true"
elements.password.options.required = "true"
elements.submit.type = "submit"
elements.submit.options.label = "Login"
displayGroups.loginform.elements.username = "username"
displayGroups.loginform.elements.password = "password"
displayGroups.loginform.elements.submit = "submit"
displayGroups.loginform.options.legend = "Login"
Login form:
class Application_Form_Login extends Zend_Form
{
public function init()
{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/forms.ini', 'login');
$this->setOptions($config->toArray());
//$this->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));
}
}
The html is very simple - no js etc. :
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Development </title>
<link href="/css/global.css" media="screen" rel="stylesheet" type="text/css" /><link href="/css/global.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/css/development.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<div id="header-logo" style="float: left"><img src="/images/small.gif" alt="Development" style="margin-top:5px" /> Development</div>
<div id="header-navigation" style="float: right">
</div>
</div>
<div id="view-content">
<div id="loginform">
<form id="login" enctype="application/x-www-form-urlencoded" action="login" method="post"><dl class="zend_form">
<dt id="loginform-label"> </dt><dd id="loginform-element"><fieldset id="fieldset-loginform"><legend>Login</legend>
<dl>
<dt id="username-label"><label for="username" class="optional">Username:</label></dt>
<dd id="username-element">
<input type="text" name="username" id="username" value="a" />
<ul class="errors"><li>'a' is less than 2 characters long</li></ul></dd>
<dt id="password-label"><label for="password" class="optional">Password:</label></dt>
<dd id="password-element">
<input type="password" name="password" id="password" value="" /></dd>
<dt id="submit-label"> </dt><dd id="submit-element">
<input type="submit" name="submit" id="submit" value="Login" /></dd></dl></fieldset></dd></dl></form> <div id="loginerror">
</div>
</div>
<div id="loginspacer"> </div>
</div>
<div id="footer">
<div id="footer-logo"></div>
<div id="footer-navigation">Quetzal Technology 2012</div>
</div>
</body>
</html>

maybe try it a little simpler and see what happens:
public function loginAction()
{
$this->_helper->layout->setLayout('layout_nomenu');
$loginForm = new Application_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
$this->_helper->redirector('users', 'grid'); //go here if valid
} else {
//go here if not valid
$this->view->loginfail = "Login details not recognised, please try again";
}
}
//if not post show form
$this->view->login = $loginForm;
}
I have to wonder if that extra loop might be causing a problem in some instances.

Related

Play! Framework - Submit button does POST to wrong link

I have an api running on AWS. I use TomCat to run my Play application. I do not know much about front end and scala, but I followed a tutorial to create a Form. The problem is: the page is ok, and I can access normally. The problem is when I click in submit button... it always leads to a wrong POST url.
This is the wrong url:
POST /myapplication/myapplication/recoverPasswordAction
It should be
POST /myapplication/recoverPasswordAction
Does anybody have any idea how to solve this?
Main.scala.html:
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>Recuperar senha</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- Load site-specific customizations after bootstrap. -->
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Recuperar senha</a>
</div>
</div>
</div>
#content
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<!-- Enable tooltips. Used primarily to validate that JQuery + Bootstrap JS are loaded. Remove this script if you don't want tooltips. -->
<script type="text/javascript">
jQuery(function ($) {
$("[rel='tooltip']").tooltip()
});
</script>
</body>
</html>
This is my fieldset.scala.html
#(changePassword: Form[views.formdata.ChangePasswordForm])
#import views.html.bootstrap3._
<fieldset>
<!-- Header -->
<div id="legend">
<legend>Recuperar Senha</legend>
</div>
<!-- Name -->
#password(changePassword("password"),
label = "Senha",
placeholder = "Nova senha",
help = "Senha com no mínimo 4 e no máximo 12 carácteres.")
<!-- Password -->
#password(changePassword("confirmPassword"),
label = "Confirmar Senha",
placeholder = "Confirme a Nova senha",
help = "")
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit" type="submit" value="Submit" class="btn btn-primary">Confirmar</button>
</div>
</div>
</fieldset>
Index.scala.html:
#(changePassword: Form[views.formdata.ChangePasswordForm])
#import helper._
#Main("Index") {
<div class="container">
<div class="well">
#form(routes.UserPasswordRecoveryController.postCreateNewPassword(), 'class -> "form-horizontal") {
#fieldset(changePassword)
}
</div>
#if(flash.containsKey("success")) {
<div class="well">
<div id="success-message" class="text-success">
#flash.get("success")
</div>
</div>
}
#if(flash.containsKey("error")) {
<div class="well">
<div id="error-message" class="text-danger">
#flash.get("error")
</div>
</div>
}
</div>
}
This is my ChangePasswordForm.java
public class ChangePasswordForm {
public String password;
public String confirmPassword;
public long userId;
private PBKDF2Generator pbkdf2Generator;
/** Required for form instantiation. */
public ChangePasswordForm() {
}
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<>();
if (password == null || password.length() == 0) {
errors.add(new ValidationError("password", "Por favor, digite uma senha."));
}else if(password.length() < 4){
errors.add(new ValidationError("password", "Por favor, digite uma senha com no mínimo 4 dígitos."));
}else if(password.length() > 12){
errors.add(new ValidationError("password", "Por favor, digite uma senha com no máximo 12 dígitos."));
}else if(confirmPassword.length() == 0 || confirmPassword.equals("")){
errors.add(new ValidationError("confirmPassword", "Por favor, digite a confirmação da senha."));
}else if(!confirmPassword.equals(password)){
errors.add(new ValidationError("confirmPassword", "Senha incorreta."));
}
if(errors.size() > 0){
return errors;
}else{
try {
String uuid = UUID.randomUUID().toString().replace("-", "");
this.pbkdf2Generator = new PBKDF2Generator();
this.password = pbkdf2Generator.generateStrongPasswordHash(password, uuid);
this.confirmPassword = pbkdf2Generator.generateStrongPasswordHash(confirmPassword, uuid);
} catch (NoSuchAlgorithmException | InvalidKeySpecException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Finally the route with the action of the button that is not being called in the right way:
POST /recoverPasswordAction controllers.UserPasswordRecoveryController.postCreateNewPassword()

Firebase Authorization and Standard Google App Engine - cannot login or signup

I have a google app engine and I recently decided to add app engine to it. I have gone through the steps, have imported my google project into firebase, added all the initialization code, and some temp functions for logging in and signing up. However, the app never goes past the points where I try to log in. I have been searching everywhere and trying everything I can. I'm sure I'm just missing something small, but could use another set of eyes. Thanks.
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<title>Hello Endpoints!</title>
<script type="text/javascript" src="/js/base.js"></script>
<!-- SCRIPT FOR FIREBASE -->
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-database.js"></script>
<script type="text/javascript" src="/js/firebaseApp.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap-responsive.css">
<link type="text/css" rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="password" placeholder="Password">
<button id="btnLogin" class="btn btn-action" onclick="loginEvent()">
Log in
</button>
<button id="btnSignUp" class="btn btn-secondary" onclick="signupEvent()">
Sign Up
</button>
<button id="btnLogout" class="btn btn-action hide">
Log out
</button>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
</script>
</div>
<div class="container">
<form action="javascript:void(0);">
<h2>Add Asteroid</h2>
<div><span class="label">Name: </span><input id="asteroidName" /></div>
<div><span class="label">Diameter: </span><input id="asteroidDiam" /></div>
<div>Dimensions:</div>
<div><span class="dimlabel">Length: </span><input id="asteroidLength" /></div>
<div><span class="dimlabel">Width: </span><input id="asteroidWidth" /></div>
<div><span class="dimlabel">Height: </span><input id="asteroidHeight" /></div>
<div><span class="label">Mean Distance From Sun: </span><input id="asteroidDist" /></div>
<div><input id="addAsteroid" type="submit" class="btn btn-small" value="Submit"></div>
</form>
<form action="javascript:void(0);">
<h2>Refresh Asteroids</h2>
<div><input id="listAsteroids" type="submit" class="btn btn-small" value="Refresh"></div>
</form>
<table id="AsteroidTable">
<tr>
<th>Asteroid</th>
<th>Diameter</th>
<th>Dimensions</th>
<th>Mean Distance From Sun</th>
</tr>
</table>
<script type="text/javascript">
function init() {
google.devrel.samples.hello.init('//' + window.location.host + '/_ah/api');
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</div>
</body>
</html>
And here is my FirebaseApp.js:
function loginEvent()
{
const email = document.getElementById('txtEmail');
const pass = document.getElementById('txtPassword');
email.value = "HELLO";
email.value = firebase.app().name;
pass.value = "NO";
firebase.auth().signInWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
pass.value = "YES"
}
function signupEvent()
{
const email = document.getElementById('txtEmail');
const pass = document.getElementById('txtPassword');
firebase.auth().createUserWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}
I was changing the values of the email and password just to make sure I was reaching that point. printing out the value of firebase.app().name returns [DEFAULT]. I also made sure email/password option was selected in Firebase. Thank you for any help you can provide.
You only need to include https://www.gstatic.com/firebasejs/4.3.1/firebase.js which contains all the modules needed. No need to include all the others: firebase-app.js, firebase-auth.js, etc.
Also signInWithEmailAndPassword and createUserWithEmailAndPassword accept string arguments. You are passing input elements instead. There should errors thrown in the console because of this. So instead of email, pass email.value.

codeigniter upload form not working

I've never used code igniter and I'm trying to make a quick admin form that includes an image upload input. My admin form is up and has a route/url that I can reach, but the save function is not working correctly. I'm getting a 404 error when I click my submit button.
I believe the issue is with the line form_open_multipart('dashboard_save/do_upload') in views/admin/Dashboard.php. I don't think the do_upload function is being reached. Any ideas where I'm going wrong?
*new detail: I am able to reach my controller with form_open_multipart('dashboard_save') using an index function... but I'm not able to reach any other function such as form_open_multipart('dashboard_save/upload') using an upload function in controller dashboard_save.
CONTROLLERS
controllers/admin/Dashboard_save.php
<?php
class Dashboard_save extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
// die('got here 2');
$this->load->view('admin/dashboard_view', array('error' => ' ' ));
}
public function do_upload()
{
// die('got here!!');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('dashboard_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('dashboard_save', $data);
}
}
}
?>
VIEWS
views/admin/Dashboard.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<!DOCTYPE html>
<body>
<div id="main-wrapper">
<div id="main-container">
<div id="main-body">
<div id='main-form-body'>
<p>Configure front end here.</p>
<div id='admin-form-container'>
<?php echo form_open_multipart('dashboard_save/do_upload');?>
<form id="admin-form" method="" action="">
<div class='form-field'>
<div class='label-wrapper'><label for='main_img'>Main Image</label></div>
<input type = "file" name = "userfile" size = "20" />
</div>
<div class='form-field'>
<button id="submit-search" type="submit" class="button" title="Submit" value = "upload">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
views/admin/Dashboard_save.php
<html>
<head><title>Dashboard Save</title></head>
<body>
<h3>testing dashbord submit</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>
Hi first to check your do_upload function has been called or not . if yes then to please check you have loaded in upload library or not . if not so please upload library and than to use below code
<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<!DOCTYPE html>
<body>
<div id="main-wrapper">
<div id="main-container">
<div id="main-body">
<div id='main-form-body'>
<p>Configure front end here.</p>
<div id='admin-form-container'>
<form id="admin-form" method="post" action="<?php echo base_url()?>/dashboard_save/do_upload" enctype="multipart/form-data">
<div class='form-field'>
<div class='label-wrapper'><label for='main_img'>Main Image</label></div>
<input type = "file" name = "userfile" size = "20" />
</div>
<div class='form-field'>
<button id="submit-search" type="submit" class="button" title="Submit" value = "upload">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
You have used two times the form tag. This is why its taking last one and showing error. Remove one FORM tag. Here is your view file code revised
<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<!DOCTYPE html>
<body>
<div id="main-wrapper">
<div id="main-container">
<div id="main-body">
<div id='main-form-body'>
<p>Configure front end here.</p>
<div id='admin-form-container'>
<?php $attributes = array('id' => 'admin-form'); echo form_open_multipart('dashboard_save/do_upload', $attributes);?>
<div class='form-field'>
<div class='label-wrapper'><label for='main_img'>Main Image</label></div>
<input type = "file" name = "userfile" size = "20" />
</div>
<div class='form-field'>
<button id="submit-search" type="submit" class="button" title="Submit" value = "upload">Submit</button>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</body>
</html>
No test it. I have removed form open & close tag which you wrote manually, at same time use only form_open_multipart() & form_close() for accomplish same task

Ionic app data from html to php server

I'm new to Ionic framework and am struggling to post data from HTML to PHP.
1.index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">HTML</h1>
</ion-header-bar>
<ion-view title="Signup">
<ion-nav-buttons side="left">
<button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-content class="has-header">
<div class="list list-inset">
<label class="item item-input">
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input">
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input">
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-positive button-dark" ng-click="signUp(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
</ion-pane>
</body>
</html>
app.js:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function () {
var request = $http({
method: "post",
url: "http://myurl.com/signup.php",
crossDomain : true,
data: {
email: $scope.email,
password: $scope.password,
username: $scope.username
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Successfully Created Account";
}
if(data == "2"){
$scope.responseMessage = "Create Account failed";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exist"
}
});
}
})
3.PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysql_connect("localhost","username",'password') or die ("Could not connect: " . mysql_error());;
mysql_select_db('dbname', $con);
$qry_em = 'select count(*) as cnt from users where email ="' . $email . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,pass,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
edit: I wrote a detailed post on how to post data from Ionic to PHP and you can view it here.
In the index.html file you have:
ng-click="signUp(userdata)
but then in the app.js file you have this:
$scope.signup = function () {
instead of something like:
$scope.signup = function (userdata) {
If you would go this route then your data should look like this:
data: {
email: userdata.email,
password: userdata.password,
username: userdata.username
}
However, you don't have to do it like this! You can do it like so that you remove the userdata from ng-click="signUp(userdata) and then in the app.js file in the data part you do it like this:
data: {
email: $scope.userdata.email,
password: $scope.userdata.password,
username: $scope.userdata.username
}

Getting the form to submit/ email

I'm trying to figure this stuff out as I'm going so some expert help and advice would be appreciated. I have a form - using jQuery and Ajax, at the moment I dont know whats working - like if I submit it echos back the data input (only one field - still need to figure out how to add more to the code) but nothing comes through to my email. Am I supposed to link it to some other PHP validation script or can it all be in one place?
Here is a link to the test space: www.bgv.co.za/testspace/contactos.php
Here is the PHP: (my syntax is probably off) - Its a combination of Validation and AJAX stuff - file is called: post.php
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
?>
Here is the JS file (Called: ajaxSubmit)
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#contactform').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#contactform').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#contactform').show(500);
}
});
return false;
});
});
and here is the HTML DOC:
<?php
/**
* #author Brett Vorster <www.kreatif.co.za>
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Orchard Systems 2012 Symposium Register Here" />
<meta name="keywords" content="Orchard Systems, Fruit Growers" />
<title>Orchard Systems 2012 | Contact Form</title>
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" media="all" href="css/styleie7.css" />
<![endif]-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append("<div id='sadhu'>This is just plain text. I need me a variable of somethink</div>");
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
</script>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
</head>
<body class="contact">
<div id="container">
<div class="sidebar">
<img src="images/orchardsystems2012.png" title="Orchard Systems 2012 Logo" />
<div class="data"><p>
10th International<br/>Symposium on<br/>Orchard Systems</p></div>
<div class="location"><p>
Stellenbosch<br/>South Africa<br/><span>3 - 6 December</span><br/>2012</p>
</div><a><img class="button" src="images/button_interested.png" title="I am interested - keep me informed" /></a>
<img class="button" src="images/button_attend.png" title="I want to attend - registration form" />
<a href="abstract.html" title="Click here to submit an abstract" ><img class="button" src="images/button_abstract.png" title="I want to take part - submit an abstract" /></a>
<img src="images/ishslogo.gif" style="margin:45px 63px 0px 63px;" />
</div>
<div id="intainer">
<div id="menu">
<ul>
<li><a href="index.html" tabindex="i" title="Orchard Systems 2012 | Home" >Home</a></li>
<li><a href="aboutus.html" tabindex="au" title="About Us" >About Us</a></li>
<li><a href="programme.html" tabindex="p" title="Programme" >Programme</a></li>
<li><a href="registration.html" tabindex="r" title="Registration Form" >Registration</a></li>
<li><a href="venue.html" tabindex="v" title="Venue" >Venue</a></li>
<li><a href="accommodation.html" tabindex="a" title="Accommodation" >Accommodation</a></li>
<li>Tours</li>
<li class="current">Contact</li>
</ul>
</div>
<div class="header">
<h3 class="pagetitle">Contact</h3>
</div>
<div id="content">
<p class="general_site">If you want to be kept in the loop please send us your details and we will update you. Suggestions for workshops are welcome.</p>
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form action="" id="contactform" method="post">
<fieldset>
<legend>Demo form</legend>
<div class="_required"><label for="name">Name*</label><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><label for="email">E-mail address*</label><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<label for="message">Message</label><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<div class="checko"><input type="checkbox" class="check" name="ISHS Member"/><label class="right" for="message">I am interested in a pre-symposium tour</label></div>
<input type="submit" value="submit" name="submit" id="submit" />
</fieldset>
</form>
<p class="general_site">Or you can contact Retha Venter on +27 82 6567088 or reventer#netactive.co.za</p>
</div>
</div>
</div>
<div id="footer">
<div class="footer_content">
<div class="copyright"><a href="http://www.kreatif.co.za" target="_blank" title="website designed and developed by Kreatif Code.Design">© Orchard Systems 2012<br/>
Designed by kreatif.co.za</a></div>
<span class="contactno">Tel +27 21 000 0000</span>
<span class="emailus">info#orchardsystems2012.co.za</span>
</div>
</div>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
</body>
</html>
Please help me, I've spent the whole weekend trying to find a way to do this. Everytime I feel like I get somewhere and it amounts to nothing... I'm no programmer I dont understand how all of this works but I am learning and just really need to know how to do it. Thank you
Sorted by adding this to the PHP file >
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
and this >
$subject = "Website Contact Form Enquiry";
$return['error'] = false;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$comments = trim($_POST['message']);
hey looks like I'm learning how this stuff works!