Form Submit with using Jquery Ajax PHP - javascript

I know there is a lot of similar questions but I am working on this exact same problem for two days and I just gave up.
So after the form is submitted, I want to prevent the current page (updates.php) to redirect to another page (test.php).
I am trying to do this with Jquery Ajax, but in this point, I am open to any solution.
updates.php:
<form action="test.php" method="post">
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary">
</div>
</form>
test.php:
<?php
$id = $_POST['id'];
$username = $_POST['name'];
$comment = $_POST['subject'];
if(!empty($username) || !empty($comment))
{
$conn = mysqli_connect('localhost','Admin','admin123','website');
if(!$conn)
{
echo "Connection Error: " . mysqli_connect_error();
}
else
{
$INSERT = "INSERT INTO comments (id, name, comment) VALUES (?,?,?)";
$stmt = $conn -> prepare($INSERT);
$stmt -> bind_param("iss", $id, $username, $comment);
$stmt -> execute();
}
}
else { echo "All fields are required"; die();}
?>
Whatever I did I couldn't stop test.php to open.

Try this as your updates.php file instead:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function submitWithAjax(){
var name = document.getElementById("name").value;
var id = document.getElementById("id").value;
var subject = document.getElementById("subject").value;
$.post( "test.php", {name: name, id: id, subject: subject})
.done(function(data) {
alert( "Data Loaded: " + data );
});
}
</script>
</head>
<body>
<form>
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary" onclick="event.preventDefault();submitWithAjax();">
</div>
</form>
</body>
</html>

Related

Can't add spaces, form to email handler

Good morning,
I'm trying to add spaces to the words on my form. Here's an example:
Sample pic
For example, the "Referralname" and "Phonenumber" should be "Referral Name" and "Phone Number".
Here's the form:
<div class="container">
<div class="row" style="margin-top: -10px;">
<div class="col-md-6 col-md-offset-3">
<h2>Referral Form <a style="font-size: 10px;" href="../index.php">Back to homepage</a></h2>
<p> Send your referrals using the form below and we will get back to you as early as possible. </p>
<form role="form" method="post" id="reused_form" enctype="multipart/form-data" >
<div class="form-group">
<label for="name"> Your Name:</label>
<input type="text" class="form-control" id="name" name="name" required maxlength="50">
</div>
<div class="form-group">
<label for="email"> Referral's Name:</label>
<input type="text" class="form-control" id="email" name="referralname" required maxlength="50">
</div>
<div class="form-group">
<label for="email"> Referral's Email:</label>
<input type="email" class="form-control" id="email" name="email" required maxlength="50">
</div>
<div class="form-group">
<label for="email"> Referral's Phone Number:</label>
<input type="text" class="form-control" id="email" name="phonenumber" required maxlength="50">
</div>
<div class="form-group">
<label for="name"> Message:</label>
<textarea class="form-control" type="textarea" name="message" id="message" placeholder="Your Message Here" maxlength="6000" rows="7"></textarea>
</div>
<div class="form-group">
<label for="name"> Upload Resumé:</label>
<input type="file" class="form-control" id="image" name="image" required>
</div>
<button type="submit" class="btn btn-lg btn-success pull-right" id="btnContactUs">Send! →</button>
</form>
<div id="success_message" style="width:100%; height:100%; display:none; "> <h3>Sent your message successfully!</h3> </div>
<div id="error_message" style="width:100%; height:100%; display:none; "> <h3>Error</h3> Sorry there was an error sending your form. </div>
</div>
</div>
</div>
And here's the php code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
Tested working with PHP5.4 and above (including PHP 7 )
*/
require_once './vendor/autoload.php';
use FormGuide\Handlx\FormHandler;
$pp = new FormHandler();
$validator = $pp->getValidator();
$validator->fields(['name', 'referralname', 'email', 'phonenumber'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
$validator->field('message')->maxLength(6000);
$pp->attachFiles(['image']);
$pp->sendEmailTo('angela.sales#teamspan.com', 'marjorie.bugayon#teamspan.com'); // ← Your email here
echo $pp->process($_POST);
private function compose_mail($post)
{
$content = "Form submission: \n\n";
foreach($post as $name=>$value)
{
$content .= ucwords($name).":\n";
$content .= "$value\n\n";
}
$this->mailer->Body = $content;
}
Sorry if my question isn't good, trying my best to make a good question.
You could do something like this
private function compose_mail($post)
{
$content = "Form submission: \n\n";
foreach($post as $name=>$value)
{
$content .= ucwords($name).":\n";
$content .= "$value\n\n";
}
$content = str_replace("Referralname", "Referral Name", $content);
$content = str_replace("Phonenumber", "Phone number", $content);
$this->mailer->Body = $content;
}
"Referral's Name" is a label. It's only good for user interaction. Your PHP code never sees it.
"referralname" is the name of an INPUT control of type "text". This is what your code uses.
You can't (or at least shoudn't) add spaces and punctuation to a field name. There's no need for them to be identical.
I think that you want that space in the body of the e-mail. So try this adding these 2 lines in php:
$content = str_ireplace('Referralname', 'Referral Name', $content);
$content = str_ireplace('Phonenumber', 'Phone Number', $content);
//right before this line:
$this->mailer->Body = $content;
Php function str_ireplace will replace the first string with the second, but only in the body of e-mail.
Str_ireplace or str_replace should be the same for you. The former is case-insensitive, the latter is case-sensitive.

Ajax to PHP Undefined Index Passed as data:

how are you doing? I can't figure out why I'm getting an Undefined Index error in my code. I've been through most of the postings on this site, and tried adding the dataType, the parentheses, using the serialize method, etc.
<!DOCTYPE html> <html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<link rel="stylesheet" href="styles/styles.css" />
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<h1 class="center-align">Welcome to the Black Archives</h1>
<p id="introparagraph">Thank you for visitng us today. We look forward to serving you. Please take the time to complete the following form. You're contact information will be stored in our system. This information will be used to keep you informed about upcoming events and exhibits. You will also receive a copy of our next newsletter. We will only use your information for museum-related purposes. Your information will not be sold or distributed to another party. For questions related to this form, please stop by the main office.</p>
<div class="myForm">
<div class="row">
<form class="col s12" action="register.php" id="registerForm" method="POST">
<div class="row">
<div class="input-field col s5">
<input placeholder="First Name" id="fname" name="fname" type="text" class="validate">
<label class="labelText" for="fname">First Name</label>
</div>
<div class="input-field col s2">
<input placeholder="Middle Initial" id="mi" name="mi" type="text" class="validate">
<label class="labelText" for="mi">Middle Initial</label>
</div>
<div class="input-field col s5">
<input placeholder="Last Name" id="lname" name="lname" type="text" class="validate">
<label class="labelText" for="lname">Last Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input placeholder="Address" id="address" name="address" type="text" class="validate">
<label class="labelText" for="address">Address</label>
</div>
<div class="input-field col s6">
<input placeholder="Address 2" id="address2" name="address2" type="text" class="validate">
<label class="labelText" for="address2">Address 2</label>
</div>
</div>
<div class="row">
<div class="input-field col s5">
<input placeholder="City" id="city" name="city" type="text" class="validate">
<label class="labelText" for="city">City</label>
</div>
<div class="input-field col s2">
<input placeholder="State" id="state" name="state" type="text" class="validate">
<label class="labelText" for="state">State</label>
</div>
<div class="input-field col s5">
<input placeholder="Postal Code" id="zipcode" name="zipocode" type="text" class="validate">
<label class="labelText" for="zipcode">Postal Code</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input placeholder="Email" id="email" name="email" type="email" class="validate">
<label class="labelText" for="email">Email Address</label>
</div>
<div class="input-field col s6">
<input placeholder="Phone" id="phone" name="phone" type="tel" class="validate">
<label class="labelText" for="phone">Phone</label>
</div>
</div>
<div class="row right-align">
<button class="btn waves-effect waves-light btn-large" type="submit" name="register" id="submitBtn">Submit<i class="material-icons right">send</i></button>
</div>
</form>
</div>
</div>
</div>
<script src="js/scripts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".input-field>label").css("color", "black");
$("#submitBtn").on('click', function () {
var fname = $("#fname").val();
var mi = $("#mi").val();
var lname = $("#lname").val();
var address = $("#address").val();
var address2 = $("#address2").val();
var city = $("#city").val();
var state = $("#state").val();
var zipcode = $("#zipcode").val();
var email = $("#email").val();
var phone = $("#phone").val();
console.log(phone);
if (fname == "") {
$('#fname').css("backgroundColor", "#f7e7e1");
}
else if (lname == "") {
$('#lname').css("backgroundColor", "#f7e7e1");
}
else {
$.ajax({
url: 'register.php',
method: 'POST',
data: { data: $('#registerForm').serialize() },
success: function (response) {
console.log("Hello World!!!");
},
dataType: 'text'
});
}
});
});
</script>
</body>
And here is the PHP document below. When Passing the data, and monitoring it via the browser's debugging tool, it shows register: with no data.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "museum";
if (isset($_POST['register'])) {
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fname = $_POST['fname'];
$mi = $_POST['mi'];
$lname = $_POST['lname'];
$address = $_POST['address'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$sql = "INSERT INTO guest (fname, mi, lname, address1, address2, city, state, zipcode, email, phone) VALUES ('$fname', '$mi', '$lname', '$address', '$address2', '$city', '$state', '$zipcode', '$email', '$phone')";
if($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
An easier way would be to add an ID to your form and add the name=""
attribute to your input fields. Then, when you're going to post them
with Ajax, all you need to do is: data: $('#the-form-id').serialize().
No need to define all the fields in JS. – Magnus Eriksson 6 hours ago
This worked, had to take out the variable initializations, and add the name attribute to each of the inputs. Then the program worked as expected.

First time using prepared statements but query is not activating

I have just started using prepared statements as it was brought to my attention by another user. However, after I started to implement it, it doesn't seem to properly add the new record to the database. When I click on Submit, it just shows the register success div that I have setup.
login.php (Where the form is located)
<form id="signupform" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<input type="text" class="form-control" name="email" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="firstname" class="col-md-3 control-label">First Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="firstname" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-md-3 control-label">Last Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="lastname" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="age" class="col-md-3 control-label">Age</label>
<div class="col-md-9">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' maxlength="3" class="form-control" name="age" placeholder="Age">
</div>
</div>
<div class="form-group">
<label for="region" class="col-md-3 control-label">Region</label>
<div class="col-md-9">
<input type="text" class="form-control" name="region" placeholder="Region">
</div>
</div>
<div class="form-group">
<label for="address" class="col-md-3 control-label">Address</label>
<div class="col-md-9">
<input type="text" class="form-control" name="address" placeholder="Address">
</div>
</div>
<div class="form-group">
<label for="Postcode" class="col-md-3 control-label">Postcode</label>
<div class="col-md-9">
<input type="text" class="form-control" name="postcode" placeholder="Postcode">
</div>
</div>
<div class="form-group">
<label for="language" class="col-md-3 control-label">Language</label>
<div class="col-md-9">
<input type="text" class="form-control" name="language" placeholder="Language">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i>Submit</button>
</div>
</div>
</form>
JavaScript:
<script type="text/javascript">
$(function() {
$("#signupform").bind('submit',function() {
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var age = $('#age').val();
var region = $('#region').val();
var address = $('#address').val();
var postcode = $('#postcode').val();
var language = $('#language').val();
$.post('scripts/register.php',{username:username, email:email, password:password, firstname:firstname, lastname:lastname, age:age, region:region, address:address, postcode:postcode, language:language}, function(data){
$('#signupsuccess').show();
}).fail(function(){{
$('#signupalert').show();
}});
return false;
});
});
</script>
register.php
<?php
include 'connection.php';
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO `users` (`ID`, `Username`, `Password`, `Email`, `First_Name`, `Last_Name`, `Age`, `Region`, `Address`, `Postcode`, `Language`) VALUES ('NULL', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
$stmt->bind_param(NULL, $username, $password, $email, $firstName, $lastName, $age, $region, $address, $postcode, $language);
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
$region = $_POST['region'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$language = $_POST['language'];
$stmt->execute();
$stmt->close();
?>
You're getting values from elements you think have id's (like #username) but none of your inputs has id="username". You can either add the id's to your input elements or you can change your selectors, e.g. $('[name="username"]')

javascript - stop refresh if error is returned from php

I was wondering whether it would be possible to add something to my javascript which would allow a refresh if the form is submitted fine however will not refresh the page if an error is returned back from PHP.
is this possible? if so could anyone provide me with any guidance that will help me achieve this please. I have manage to get the javascript to refresh when the form is submitted and a message is returned.
this is the js:
function addCall() {
var data = $('#addForm').serialize();
$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){
$("#addForm").html(response);
//'soft'reload parent page, after a delay to show message
setTimeout(function(){
$('#addModal').modal('hide')
location.reload();
},3500);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
and the php which processes the form and validates it:
<?php
session_start();
if (empty($_POST['course_title'])) {
$message = " Value is required";
}
else {
$course_title = trim($_POST['course_title']);
# Validate Course #
if (!ctype_alpha($course_title)) {
$message = '<p class="error">Course title should be alpha characters only.</p>';
}
elseif (strlen($course_title) < 3 OR strlen($course_title) > 50) {
$message = '<p class="error">Course title should be within 3-50 characters long.</p>';
}
else {
include "../includes/db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`) VALUES (:course_title)");
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
$sql->execute();
$message = "<p class='text-success'> Record Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e) {
if( $e->getCode() == 23000)
{
$message = 'Course already exists in database';
}
else
{
$message = $e->getMessage();
}
}
}
}
die($message);
?>
It would really useful to the user to be able to make amendments to the form instead of rewriting it all again.
the form:
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add New Record: </h4>
</div>
<div class="modal-body">
<form id="addForm" class="addForm">
<div class="form-group">
<label class="control-label" for="forename">Forename:</label>
<div class="controls">
<input id="forename" name="forename" type="text" placeholder="Enter forename(s)" class="form-control" maxlength="100" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="surname">Surname:</label>
<div class="controls">
<input id="surname" name="surname" type="text" placeholder="Enter surname" class="form-control" maxlength="100" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input id="email" name="email" type="email" placeholder="Enter a valid email" class="form-control" maxlength="255" value="" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="username">Username:</label>
<div class="controls">
<input id="username" name="username" type="text" placeholder="username" class="form-control" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="password">Password:</label>
<div class="controls">
<input id="password" name="password" type="password" placeholder="password" class="form-control" maxlength="40" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="confirm_password">Confirm Password:</label>
<div class="controls">
<input id="confirm_password" name="confirm_password" type="password" placeholder="retype password" class="form-control" maxlength="40" required="">
</div>
</div>
<?php
include "../includes/db_conx.php";
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt2 = $db_conx->prepare('SELECT * FROM role_type');
$stmt2->execute();
$roles = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<div class="control-group">
<label class="control-label" for="role_type">Select User Type:</label><p></p>
<select name="role">
<option value=''>Select One</option>";
<?php foreach($roles as $role): ?>
<option value="<?php echo $role['role_type_code'] ?>"><?php echo $role['role_title'] ?></option>
<?php endforeach ?>
</select>
</div>
<p></p>
<?php
include "../includes/db_conx.php";
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt3 = $db_conx->prepare('SELECT * FROM course_details ORDER BY course_title');
$stmt3->execute();
$courses = $stmt3->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<div class="control-group">
<label class="control-label" for="course_details">Select Course:</label><p></p>
<select name="course">
<option value=''>Select One</option>";
<?php foreach($courses as $course): ?>
<option value="<?php echo $course['course_code'] ?>"><?php echo $course['course_title'] ?></option>
<?php endforeach ?>
</select>
</div>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
</form>
</div>
<div class="modal-footer">
<div class="btn-toolbar">
<button type="button" class="btn btn-default" class="pull-right" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" class="pull-right" onclick="addUCall();">Submit <span class="glyphicon glyphicon-saved"></button>
</div>
</div>
</div>
</div>
</div>
Thank you in advance.
Your message variable contain both error and success message. It will reload page every time when it receives response.
Add this after $("#addForm").html(response); -
var n = response.search("class=\'text-success\'");
if(n!=-1){
//reload success
}
else{
//stay on page, errors
}
As you're returning the error messages in the response, check for the error class and do the reload if necessary.
$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){
if(response.contains("text-success")) {
// put your logic here for success
} else {
// logic for errors
}
});

A singular behavior about a Registration form in PHP

I have a registration form in my (project of) website of the following form: (i used bootstrap framework):
<div id="main-box" class="container">
<div class="row-fluid">
<div id="signup">
<div id="float"></div>
<div id="center_signup">
<h3>Registrazione Studente</h3>
<?php if (isset($registerError)): ?>
<p><?php htmlout($registerError); ?></p>
<?php endif; ?>
<form action="" method="post" class="form-horizontal">
<div class="form-group">
<label for="nome" class="col-sm-2 control-label">Nome: </label>
<div class="col-sm-6">
<input type="text" name="nome" id="nome" class="form-control">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email: </label>
<div class="col-sm-6">
<input type="text" name="email" id="email" class="form-control">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-6">
<input type="password" name="password" id="password" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Now the data of the form are managed from a index.php controller file, which do this (the register.html.php file is the template file in which there is the code above):
if (isset($_GET['register']))
{
include 'register.html.php';
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['registerError'] = 'fill in both fields';
exit();
}
$password = md5($_POST['password'] . 'figarodb');
if (databaseContainsUser($_POST['email'], $password))
{
$GLOBALS['registerError'] = 'Student already registered.';
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/figaro/includes/db.inc.php';
// Puts the student in the relevant table
try
{
$sql = 'INSERT INTO studente SET
nome = :nome,
email = :email,
password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':nome', $_POST['nome']);
$s->bindValue(':email', $_POST['email']);
$s->bindValue(':password', $password);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Errore in student registration.';
include $_SERVER['DOCUMENT_ROOT'] . '/figaro/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
This header might redirect at the home page, but it doesn't do it!
If instead of the page with bootstrap and javascript code, i modify the registration page in this way:
<body>
<h1>Registration</h1>
<form action="" method="post">
<?php if (isset($registerError)): ?>
<p><?php echo $registerError; ?></p>
<?php endif; ?>
<div>
<label for="name">Nome completo: <input type="text" name="nome"
id="nome"></label>
</div>
<div>
<label for="email">Email: <input type="text" name="email"
id="email"></label>
</div>
<div>
<label for="password">Password: <input type="password"
name="password" id="password"></label>
</div>
<div>
<input type="submit" value="Invio">
</div>
</form>
</body>
now the controller redirect at the home page correctly!
I can not explain this behavior, any help will be greatly appreciated!Thanks!
In your php file there is written :
header('Location: .');
Maybe your web application is redirected on index.html by default because it's the default root.

Categories

Resources