Syntax Errors?

I’m late to this party, but some thoughts on this:


<?php
	class CategoryFinder
	{
		public function getCategory()
		{
			$currentURL= $_SERVER['PHP_SELF'];
			if (preg_match($currentURL, "index"))
				return "Home Page";
			elseif (preg_match($currentURL, "health"))
				return "Health";
			elseif (preg_match($currentURL, "insurance"))
				return "Insurance";
			elseif (preg_match($currentURL, "general"))
				return "General";
			elseif (preg_match($currentURL, "dating"))
				return "Dating";
			elseif (preg_match($currentURL, "education"))
				return "Education";
			elseif (preg_match($currentURL, "legal"))
				return "Legal";
			elseif (preg_match($currentURL, "startyour"))
				return "Business Opportunities";
			elseif (preg_match($currentURL, "business"))
				return "Business Services";
		}
	}
?>

This avoids the hidden dependency on SERVER vars, you can send in the SERVER var as an argument, or use it in other places now.


function getCategory($currentURL = 'index'){  // optionally set a default here in case it gets called with no args

// maintain an array of services, easier to read and add/delete entries
// you are less likely to make a typing error
// avoids using regexes in a loop too
// this could be imported from somewhere else also

$lookup = array(
'business' =>'Business Services',
'dating' =>'Dating',
'education' =>'Education',
'general' =>'General',
'health' =>'Health',
'index' =>'Home page',
'insurance' =>'Insurance',
'legal' =>'Legal',
'startyour' =>'Business Opportunities',
);

  if(array_key_exists($currentURL, $lookup) ) {
    return $lookup[$currentURL];
  }else{
    return 'Home Page';  // or something else
  }

}

echo getCategory("education");
echo getCategory("some old crap");
echo getCategory();

Gives:

Education
Home Page
Home Page

When you are clear about how you want to handle failure, that code could be tidied up more.

Might be better called categoryLookup(), though that is more a trivial personal POV.

I see what you’re saying. I guess SERVER variables, or any global variables, are not desirable in one’s code and should be avoided- for some reason I’m unclear on.

As far as error handling goes, the code may continue on uninhibited regardless of success or failure. It’s just a little something extra for me to know about a new user.

There is no room for human input error. There is no section for typing in the category. It is automatically computed, and the user does not know their “category” has been filed.

Anyway:
I specified the action attribute for the original form submit to direct the browser from index.php to showwindow.html, which is the original index page plus the form markup for the name, age, etc. I’m sure some of you understand how it’s been set up so far. Maybe this isn’t set up correctly for just simply graying out the rest of the page and displaying the 2nd form after the user originally input their e-mail address on index.php at worldreviewgroup.com. Is there a better way to do this than currently? I’ve seen this same effect on many websites.

As far as the styles go for showwindow.html, I made a post in the CSS section to find out why I’m not seeing any styles applied to showwindow.html. If you can be of assistance there, the thread is located here

The reason for this specifically is re-usability. If your class depends on the SERVER variable, you can’t reuse the class unless that SERVER variable is populated or available. By passing in the SERVER variable value either through your constructor or method as a parameter, you have just increased your re-usability by 10 fold. You can now call that class from anywhere without any dependency to the SERVER variable (you can pass in the value you want it to use) so it performs the task you expect.

Thanks for that explanation. I learned more about web development.

However- as my general strategy: I’m still looking to confirm that I’m on the right track.

-when user inputs the e-mail address originally, I am attempting to open another html file with the same markup plus an extra form.
-The background except the new form is wrapped in a div with an id of #graymask. That would make a gray, opaque box around all the other content, rendering it inactive, and leave the 2nd confirmation form open.

Thanks for your help.

Oh, well. It looks like everyone has left the party.

Can’t really ask for too much when the responses are provided free of charge.

Gonna go try to find some good examples of PHP forms that do something similar to what I’m trying to do.

Don’t know why I’m being discouraged from echoing any HTML. This example echoes the HTML results, which seems a practical solution for this project.

http://www.tizag.com/phpT/examples/formexample.php

When your user sends away the first form, use Javascript to catch it. Javascript then modifies the HTML so that DIV with #graymask comes on and the second form goes from #hidden to showing without the graymask. That would also not require loading a new page.

As for not wanting to echo html from program logic, think reusability. suddenly you need to change something in the next project or even in this project, having to go in each class and modify echo commands, or having to do it elsewhere? Have a thought on templating. If you use a simple php template which takes simple php array values and outputs them simple and easy you have removed the need of presentation from your logic.

For an easier time programming try separating files as to what they do: Data access(Model), Templates(View), Controller(Logic).

So take a short example. There is an error with the user submitted email adress… Store the error in an array, or variable, then load in the template for error handling and let it output the error. ONE look, many errors.

Hope you make sense of this, PHP is great once you get the swing of it.

I think it is because the 2nd part of your last question veered off into GUI-land code “gray, opaque box”, by all means have some conditional PHP logic which inserts some more <div> tags, but the class/styles/ids of them is up to you - we’d be unlikely to suggest what they should be or which tool you should use for such light-box style of voodoo.

as for:

-when user inputs the e-mail address originally, I am attempting to open another html file with the same markup plus an extra form.

In pseudocode you could:


if( email is clearly wrong){
// relocate to a different form
Header("Location differentform.php";
}

OR


if( email is clearly wrong){
// relocate to the same form, but set a GET flag
Header("Location sameform.php?err=1";
}

OR


if( email is clearly wrong){
repopulate the form you just showed them
grey it out
add the new input box
}

Okay, I have read and studied your replies carefully.

My main goal, or desire, in this is to keep the user on one page through this process.

I have been trying to learn how to load & display the contents of another HTML/PHP file in the same PHP file I have as my home page, index.php, but I have had no such luck. I tried the readfile() and file_get_contents() methods with no success. Maybe this means I require JS or jQuery or AJAX, but I’m just remembering every time I ask a question about JavaScript, I’m discouraged from using it because “the user may have JavaScript turned off”.

Here’s what I tried:

First form HTML:


<form id="emailbox" name="form1" method="post" action="?">
        <div>
          <input type="text" name="go" id="go" value="your e-mail" onclick="input_focus(this)"  onblur="input_reset(this)" maxlength="60"/>
          <input type="submit" value="Join" onclick="seeWhatHappened()" />
        </div>
      </form>

index.php code:


function seeWhatHappened()
		  {
			  include 'Scripts/finalactions.php';
			  $error = new FinalActions;
                          //see if the user actually input a value
			  if (isset($_POST["go"])){
			  	$email = $_POST["go"];
                                //check the input for e-mail address validity
				if (isItAValidEmail($email)){
                                        //SHOW THE CONFIRMATION FORM - this is the area I'm currently focusing on.
                                        //Either PHP has real shortcomings here and I need JavaScript, or I have done something incorrectly.
					$confirmForm = readfile("showwindow.php");
					echo $confirmForm;
				} else
					$error -> invalidEntry();
			  }
			  else
			  	$error -> invalidEntry();
		  }

showwindow.php currently has the following inside of it:


<!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" />
   	<link href="style/main.css" rel="stylesheet" type="text/css" media="screen, projection, tv" />
    <link href="style/emailsubmit.css" rel="stylesheet" type="text/css" media="screen, projection, tv" />
    <link href="style/dropdownmenus.css" rel="stylesheet" type="text/css" media="screen, projection, tv" />
    <title>Join the Mailing List at World Review Group!</title>
</head>
	<body>
		<div id="formsubmit">
					<form name="form2" id="form2" method="post" action="postsubmission.php">
					  <label for="confirmemail">Confirm your e-mail:<span>*</span></label>          
					  <input type="text" name="confirmemail" id="confirmemail" value="" maxlength="60"/><br />
					  <label for="name">Enter your name:<span>*</span></label>
					  <input type="text" name="name" id="name" value="" maxlength="60" /><br />
					  <label for="age">Select your age range:</label>
                      <select name="age" id="age">
                      	<option selected="selected">18&ndash;35</option>
                        <option>36&ndash;55</option>
                        <option>55+</option>
                        <option>17 or younger</option>
                      </select><br />
					  <label for="country">Select your country:<span>*</span></label>
					  <select name="country" id="country">
							 <option selected="selected">United States</option>
							 <option>United Kingdom</option>
							 <option>Canada</option>
							 <option>Australia</option>
							 <option>Russia</option>
							 <option>Brazil</option>
							 <option>Somewhere else</option>
					   </select><br />
					   <input type="submit" value="Sign Me Up!" onclick="checkEmail()"/>
					</form>
<?php
	class FormProcess
	{
		public function getEmail()
		{
			include 'index.php';
			$emailPasser = new PassEmail;
			$origEmail = $emailPasser -> postEmail();
			return $origEmail;
		}
		
		public function checkEmail()
		{
			include 'Scripts/finalactions.php';
			$error = new FinalActions;
			$origEmail = getEmail();
			$confirmEmail = $_POST["confirmemail"];
			if ($origEmail == $confirmEmail){
				if (isset($_POST["name"])){
					$name = $_POST["name"];
					$age = $_POST["age"];
					$country = $_POST["country"];
					include 'Scripts/categoryfinder.php';
					$categoryFinder = new CategoryFinder;
					$category = $categoryFinder -> getCategory();
					
					include 'Scripts/databasewriter.php';
					$dbWriter = new DatabaseWriter;
					$dbWriter -> writeUserToDatabase();
				} else {
					$error -> invalidEntry();
				}
			} else {
				$error -> invalidEntry();
			}
		}
	}
?>
		</div>              
	</body>
</html>

I don’t really mind the page refresh if I end up using PHP only (since it’s a server-side language), but it is nifty that JS can just load/show the next step without refresh (client-side code).

I’M REALLY STUCK!

For the php “readfile(“showwindow.php”);”
Try include() or require(), or if you only want it ONCE include_once() and require_once()

So, my strategy has been switched up to a jQuery/PHP-combo so the page does not have to redirected/refreshed, and right now I’m trying to return the necessary results from the PHP code into the jQuery/JavaScript side so that I can run code to show/hide the forms as I need to and change an element with a message on the client-side.

index.php is changed back to index.html


 <div id="rightside">
    <div id="rightsidestart">&nbsp;</div>
    <div id="rightsidebody">
      <h2 class="sideWindowHeaderText">Not Recommended</h2>
      <ul class="sideWindowLinks">
        <li><a href="#">Anthony Morrison&apos;s Big Profits Secret</a></li>
        <li><a href="#">Mobile Mass Media</a></li>
        <li><a href="#">Prorexin</a></li>
      </ul>
      <form id="emailbox" name="form1" method="post" action="?">
        <div>
          <input type="text" name="go" id="go" value="your e-mail" onclick="input_focus(this)"  onblur="input_reset(this)" maxlength="60"/>
          <input type="submit" value="Join" onclick="processor()" />
        </div>
      </form>
    </div>
    <div id="rightsideend">&nbsp;</div>
  </div>
  <!-- end side windows -->
  <div id="confirmform">
    <form name="form2" id="submissionform" method="post" action="?">
    <div>
      <label for="confirmemail" class="fixedwidth">Confirm your e-mail:<span>*</span></label>
      <input type="text" name="confirmemail" class="fixedwidth" value="" maxlength="60" class="inputwidth"/>
    </div>
    <div>
      <label for="name" class="fixedwidth">Enter your name:<span>*</span></label>
      <input type="text" name="name" class="fixedwidth" value="" maxlength="60" class="inputwidth"/>
    </div>
    <div>
      <label for="age" class="fixedwidth">Select your age range:</label>
      <select name="age" class="inputwidth">
         <option selected="selected">18&ndash;35</option>
         <option>36&ndash;55</option>
         <option>55+</option>
         <option>17 or younger</option>
      </select>
    </div>
    <div>
      <label for="country" class="fixedwidth">Select your country:<span>*</span></label>
      <select name="country" class="inputwidth">
          <option selected="selected">Select Country</option>
          <option>United States</option>
          <option>United Kingdom</option>
          <option>Canada</option>
          <option>Australia</option>
          <option>Russia</option>
          <option>Brazil</option>
          <option>Somewhere else</option>
      </select>
     </div>
     <p id="errormessage">You didn&apos;t enter the same e-mail address!</p>
      <input type="submit" value="Sign Me Up!" class="formsubmitbutton" onclick="checkSubmission()" id="2ndstep"/>
      <input type="submit" value="Cancel" class="formsubmitbutton" onclick="backToHomePage()"/>
    </form>
  </div>
  <div id="successorfailure">
  	<h4>Submission Failure</h4>
  	<p id="postsubmissionmessage">Your submission has failed.</p>
  </div>
</div><!-- end container -->
<script type="text/javascript" src="Scripts/jQuery.js"></script>
<script type="text/javascript" src="Scripts/emailbox.js"></script>

emailbox.js


function input_focus(obj){
	if ( obj.value == obj.defaultValue ){
		obj.value = ""
	}
}

function input_reset(obj){
	obj.value = obj.defaultValue;
}

$(document).ready(function(){
    //When the submit button is clicked
    $("#origemailform").on("click", function(){
                //Post the form data serialized for the proper formatting
                $.post("emailtester.php",$("#emailbox").serialize()
                //Get the response from process.php
                , function(response){
                        //Prepend the response to div id step2
                        $("#confirmform").prepend($(response).fadeIn("slow"));
				});
	$("#2ndstep").on("click", function(){
                });
    });
});

emailtester.php


<?php
	class ProcessFirstEmail
	{
		function processor()
		{
			$email = $_POST['go'];
			if ($email != "your e-mail"){
				if (isset($email))
				{
					if (isItAValidEmail($email))
					{
						return true;
					} else {
						echo $email . 'is not a valid e-mail address.';
						return false;
					}
				} else {
					echo 'There\\'s nothing in the e-mail box!';
					return false;
				}
			} else {
				return false;
				die();
			}
		}
		
		public function isItAValidEmail($email)
		{
			if (filter_var($email, FILTER_VALIDATE_EMAIL))
				return true;
			else
				return false;
		}
	}
?>

confirmform.php


<?php
	class CheckForm
	{
		public function checkSubmission()
			{
				if ($_POST['country'] != "Select Country")
				{
					if (isset($_POST['confirmemail']) && isset($_POST['name']))
					{
						$origEmail = $_POST['go'];
						$confirmEmail = $_POST['confirmemail'];
						if ($origEmail == $confirmEmail)
						{
							$name = htmlspecialchars($_POST['name']);
							$ageRange = $_POST['age'];
							$country = $_POST['country'];
							
							include 'Scripts/databasewriter.php';
							$dbWriter = new DatabaseWriter;
							$dbWriter -> writeUserToDatabase($confirmEmail, $name, $ageRange, $country, $category);
						} else {
							die();
						}
					} else {
						return false;
					}
				} else {
					return false;
				}
			}
	}
?>

How do I return results from the PHP to the jQuery saying that it is a valid entry, and, therefore, it should show the next form??