I am trying to figure out the proper way to submit a form via php:
In part I have two questions: 1 specifically about the site that I am working on, and another about form submitting in general.
Question 1. I am using php as a template for my website. so I have one index.php page with a header and footer and all of my content is pulled in from a php function like so:
<article id="main">
<?php
$page = $_GET['page'];
if(empty($page)){
$page = 'home';
}
$page.='.php';
if(file_exists("pages/$page")) {
include("pages/$page");
} else {
echo "$page no exist";
}
?>
</article>
This is the code I am using for my form, and am using it in the head tag of my index.php page:
<head>
<?php
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
</head>
And the html form code:
<form method="post" action="index.php">
<legend>Contact Us</legend>
<fieldset>
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here">
</fieldset>
<input id="submit" name="submit" type="submit" value="Submit">
</form>
When I submit the form it refreshes and puts my echo message into my index.php?page=home page instead of my index.php?page=contact page. How would I get the echo to stay on the same page of the form? (I have tried changing the action=" " part of the form but cant seem to get it to work).
Question 2. In general when I have been inspecting other web pages to see their form code I have been seeing this everywhere:
try
{
for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++)
{
var lastpass_f = document.forms[lastpass_iter];
if(typeof(lastpass_f.lpsubmitorig2)=="undefined")
{
lastpass_f.lpsubmitorig2 = lastpass_f.submit;
lastpass_f.submit = function(){
var form=this;
var customEvent = document.createEvent("Event");
customEvent.initEvent("lpCustomEvent", true, true);
var d = document.getElementById("hiddenlpsubmitdiv");
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i]==form)
{
d.innerText=i;
}
}
d.dispatchEvent(customEvent);
form.lpsubmitorig2();
}
}
}
}
catch(e){}
Is anyone familiar with the above code? And if so, is there a general script for properly submitting forms?
Thanks!