Executing PHP on Client Side Using jQuery and Returning Results/Data into jQuery

Hello all,

I have a question about what needs to be written in my PHP script to return a message/or HTML content that will be accessed through the jQuery .post() method. This is a way I learned to run client-side code without a page refresh or redirection.

PHP
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;
				}
			}
	}
?>

jQuery:


$(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(){
                });
    });
});

HTML form markup:


<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="successfulsubmit">
  	<h4>Submission Successful</h4>
  	<p id="postsubmissionmessage">Your submission was successful. Thank you for signing up!</p>
  </div>
</div><!-- end container -->
<script type="text/javascript" src="Scripts/jQuery.js"></script>
<script type="text/javascript" src="Scripts/emailbox.js"></script>
</body>
</html>

Here’s a screenshot with an emphasis on the red text, which would contain the error message for an unsuccessful submission that my PHP code needs to communicate to jQuery:
Screenshot

I’m also trying to learn how to tell jQuery that the info submitted is valid and show the next step, if I haven’t already coded that part. Haven’t found a good reading resource on this subject.

okay, lets just get one misnaming/misconception corrected first off;

the PHP will not be executed client side. PHP is only ever executed server-side. JQuery (or AJAX, or whatever), is still sending a second page request to simply ‘go get the result’. Otherwise you’d have a rather large security breach in PHP :smiley:

Now; as to why your script will do nothing.

Your jquery requests emailtester.php; which is fine.
emailtester.php contains only a class definition. Which is fine, but does absolutely nothing. Defining a class does not invoke an instance of the class. If you want that page to actually DO something, you’ll need to invoke an instance and make it do something.

Okay, here, I added at the top:


<?php
	$instance = new ProcessFirstEmail;
	$instance -> processor();

	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;
		}
	}
?>

Do I need to return or echo HTML markup for the red error message text?

I assume prepend takes in HTML; so yeah, if you want it red, you’ll need to echo out the HTML. (or return it, and echo out the return value)

Okay, I added these HTML tags with the style attribute filled in with stuff, since I apparently can’t use a class or id.


} else {
						echo '<p style="color:red; font-weight:bold; font-size:12px;">Sorry, ' . $email . ' is not a valid e-mail address.</p>';
						return false;
					}
				} else {
					echo '<div style="background:url("successorfailure.gif"); width="360px"; height="100px"; <p style="color:red; font-weight:bold; font-size:12px;">There\\'s nothing in the e-mail box!</p>';
					return false;
				}
			} else {
				return false;
				die();
			}
		}
		
		public function isItAValidEmail($email)
		{
			if (filter_var($email, FILTER_VALIDATE_EMAIL))
				return true;
			else {
				echo '<p style="color:red; font-weight:bold; font-size:12px;">That\\'s not a valid e-mail!</p>';
				return false;
			}

Now, this leaves the questions:

  1. Where will it actually place this HTML? It seems as though these error messages are going to end up somewhere completely random.
  2. Is the jQuery going to show/hide this at the correct time?

Those… are jQuery questions. I therefore forward this thread to the appropriate forum for response, as I am not a jQuery person. Moderators. AWAY!

Actually, this should make a nice box. I’m getting confused that this is weighing and handling the first email submission.


<?php
	$instance = new ProcessFirstEmail;
	$instance -> processor();

	class ProcessFirstEmail
	{
		function processor()
		{
			$email = $_POST['go'];
			if ($email != "your e-mail"){
				if (isset($email))
				{
					$firstMarkup = '<div style="background:url("successorfailure.gif"); width="360px"; height:100px; position:absolute; bottom:350px; left:508px;"><h4 style="text-shadow:1px 1px 1px #900; margin:0; padding:8px 10px 1px 12px;">Submission Failure</h4><p style="color:red; font-weight:bold; font-size:12px;">';
					if (isItAValidEmail($email))
					{
						return true;
					} else {
						echo $firstMarkup + 'Sorry, ' . $email . ' is not a valid e-mail address.</p></div>';
						return false;
					}
				} else {
					echo $firstMarkup + 'There\\'s nothing in the e-mail box!</p></div>';
					return false;
				}
			} else {
				return false;
				die();
			}
		}
		
		public function isItAValidEmail($email)
		{
			if (filter_var($email, FILTER_VALIDATE_EMAIL))
				return true;
			else 
				return false;
		}
	}
?>

Okay, I’ll take my jQuery questions to the appropriate forum.

Hi,

You may consider doing something like:


/* A input form field with an id of email_form and the specific field is the class */
var ea = $("#email_form .email_address_in").val(); 
/* A text form field */
var bd = $("#email_form .body_in").val()
$.post(
    "./libs/email/ajax_email.php"
    , { email_address : ea
        , email_body: bd
       }
     , function(data){
         //alert(data);
         some_function_to_run_after_the_data_is_returned_from_the_php_script();
});

Then in the ajax_email.php you need something like:


$email_address = htmlentities($_POST['email_address'];
$email_body = htmlentities($_POST['email_body'];

// Do your email stuff

/* echo data to return to the ajax calling page in the JavaScript data variable shown in the $.post callback variable called 'data' */
echo $result;

Okay, this is an interesting change-up on the jQuery side, and I hope it fits a way to fit my goals as demonstrated below in screenshots. I want to avoid page refresh and no page redirection. This is what I have currently in there:

The JavaScript:


//changes the input's value when it is selected
function input_focus(obj){
	if ( obj.value == obj.defaultValue ){
		obj.value = ""
	}
}

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

$(document).ready(function(){
	$("#submissionform").hide()
	
    //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
                        $("#submissionform").prepend($(response).fadeIn("slow"));
				});
	$("#2ndstep").on("click", function(){
					$.post("confirmform.php", $("#confirmform").serialize()
					, function(response){
						$("#errormessage").prepend($(response).show())
					});
                });
    });
});

the form markup:


  <!-- begin rightside div -->
  <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><!-- end container -->
<script type="text/javascript" src="Scripts/jQuery.js"></script>
<script type="text/javascript" src="Scripts/emailbox.js"></script>
</body>
</html>

emailtester.php


<?php
	$instance = new ProcessFirstEmail;
	$instance -> processor();

	class ProcessFirstEmail
	{
		function processor()
		{
			$email = $_POST['go'];
			if ($email != "your e-mail"){
				$firstMarkup = '<div style="background:url("successorfailure.gif"); width:360px; height:100px; position:absolute; bottom:350px; left:508px;"><h4 style="text-shadow:1px 1px 1px #900; margin:0; padding:8px 10px 1px 12px;">Submission Failure</h4><p style="color:red; font-weight:bold; font-size:12px; margin:0; padding:2px 0 2px 17px;">';
				if (isset($email))
				{
					if (isItAValidEmail($email))
					{
						return true;
					} else {
						echo $firstMarkup . 'Sorry, ' . $email . ' is not a valid e-mail address.</p></div>';
						return false;
					}
				} else {
					echo $firstMarkup . 'There\\'s nothing in the e-mail box!</p></div>';
					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
	$instance = new CheckForm;
	$instance -> checkSubmission();
	
	class CheckForm
	{
		public function checkSubmission()
		{
			$htmlTag = '<p style="color:red; font-weight:bold; font-size:12px">';
				
			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 {
						echo $htmlTag . 'The first e-mail is not the same as the confirmed e-mail address.</p>';
						die();
					}
				} else {
					if (!isset($_POST['confirmemail'])){
						echo $htmlTag . 'You forgot to confirm your e-mail address.</p>';
						return false;
					} elseif (!isset($_POST['name'])) {	
						echo $htmlTag . 'There is no name specified.</p>';
						return false;
					}
				}
			} else {
				echo $htmlTag . 'There is no country selected</p>';
				return false;
			}
		}
	}
?>

Here’s a screenshot preview of what my goals look like.

This is what the First Step Looks Like Before it All Takes Place
Assuming the original e-mail is good & acceptable, this is what would happen for the next step
If there are errors on the next form, confirmform.php will return the text that is red and appears below the input fields
This is the successful submission screen that will disappear along with the other form and go back to normal in just a few moments

Hi etidd,

in Post 1 you asked

I have a question about what needs to be written in my PHP script to return a message/or HTML content that will be accessed through the jQuery .post() method.

The mechanics are what I showed you in Post 8. The general method is:

  1. Use your JavaScript and JQuery scripts collect values you need to pass to your .php file.
  2. Store any data collected from forms, set them to JavaScript variables
  3. Issue an ajax $.post using JQuery, pass the JavaScript variables into the post names and values (the variables) as post name and data pairs.
  4. When the PHP file is called then parse the posted data by post name and set to a php variable
  5. Do what you need in the PHP file. In your case you have filters to validate so you can instantiate your classes and run through the validation classes. You can pass whatever data you need between these PHP classes the JQuery callback has not been serviced until you echo a response, so you can ensure that each PHP class that does something only communicates with the PHP classes or code that invoked the class. If everything validates then you echo a message that will trigger the JQUERY callback that will exist in the data variable. You can return arrays, JSON or serialized data back to JQUERY but the echoing method keeps it simple to start with so I recommend you only echo a success or failure message on your pop-up window.
  6. The callback has been issues and the JQuery data variable has a response from the PHP page. You then can use JQuery or JavaScript to target an ID on the pop-up window where the data variable contains, which should be either a success or failure message.
  7. You can use an even timer to fade the message after a period of time or fade it out after a person types again in the sign-up pop-up form after they’ve got a failure message.

Rather than do multiple $.post calls to run different PHP scripts that have different responsibilities I like to call a PHP a routing script that initializes the PHP classes that are needed. I then process what is needed (which can include inserting or editing database data) and when I get the result of the processing I return a result code. I have JavaScript match the code and put the message that is relative to the code.

Regards,
Steve

Now, I’m trying to pass only the email address to the PHP script for the first .post() call still.

I don’t have a class for the first e-mail field- it just has an id of #go. The other fields have classes of .inputwidth. So I guess I need to fill these in accordingly.

How do I get the results of the echo from the first PHP script and weigh their outcomes and show next step or display an error? Is that an idea of what is to go inside of that function?


var emailaddress = $("#go .email_address_in").val(); 
/* A text form field */
var confirmemail = $("#confirmemail .body_in").val()
var name = $("#name .body_in").val()
var agerange = $("#age .body_in")

$.post(
    "emailtester.php"
    , { email_address : emailaddress
       }
     , function(data){
         alert(data);
         doStuffButIDontKnowWhatIWillDoYet();
});

function doStuffButIDontKnowWhatIWillDoYet() {
  alert('hi');
}


<?php
	$instance = new ProcessFirstEmail;
	$instance -> processor();

	class ProcessFirstEmail
	{
		function processor()
		{
			$email = $_POST['go'];
			if ($email != "your e-mail"){
				if (isset($email))
				{
					if (isItAValidEmail($email))
					{
						echo 'Submission Successful';
					} else {
						echo 'Submission Failure- Invalid E-mail';
					}
				} else {
					die();
					echo 'Submission Failure- Nothing in Box';
				}
			} else {
				die();
			}
		}
		
		public function isItAValidEmail($email)
		{
			if (filter_var($email, FILTER_VALIDATE_EMAIL))
				return true;
			else 
				return false;
		}
	}
?>

Hi,

Ok I’ve stripped it back al little to keep this simpler for you. I’ve also changed the setup a little using an intermiderary php file to accept the ajax request and invoke any classes or functions that need to occur prior to echoing back to the JQUERY $.post function.

So here is the basic form:


<form>
  <input id='go' name='email_address' class='email_address_in'/>
  <input id='confirm_email' name='confirm_email' class='confirm_email_addresss_in' />
</form>

Here is the JQuery script again (simplified)


var ea = $("#go .email_address_in").val(); 
var bd = $("#email_form .body_in").val()
$.post(
    "./libs/email/ajax_email.php"
    , { email_address : ea}
     , function(data){
         show_email_success(data);
})


show_email_success(data){
 /*update using JQuery the id of the status message in your popup*/
}

The ajax_email.php file:


<?php
/* ajax_email.php */


require_once('ProcessEmail.php');






if($_POST['go']){
  $email = htmlentities($_POST['go']);
} else {
  echo 'Failure - missing email'
}


$obj_PE = new ProcessEmail();
$email_status = $obj_PE->processor($email);


echo $email_status;


?>

And a modified ProcessEmail class as ProcessEmail.php


/* CLASS ProccessEmail */
    class ProcessEmail
    {
	protected $email_address;
        public function processor($email)
        {
	    $this->email_address = $email;


            if ($email != "your e-mail"){
              
                    if (isItAValidEmail($email))
                    {
                        return 'Submission Successful';
                    } else {
                        return 'Submission Failure- Invalid E-mail';
                    }
	    } else {
		die();
		echo 'Submission Failure- Nothing in Box';
	    }
        }
        
        protected function isItAValidEmail()
        {
            if (filter_var($this->email, FILTER_VALIDATE_EMAIL))
                return true;
            else 
                return false;
        }
    }

You can see that initially the JQuery $.post function is called. It calls the ajax_email.php file. The ajax_email.php file requires the ProcessEmail.php file. It then tests if the $_POST[‘go’] variable exists. Normally you would do a lot more checking of this posted value, but I’ve kept it simple for this illustration. If the email exists, then we instantiate the ProcessEmail instance and then call the processor() method passing it the email. You can see that the ProcessEmail class does not echo values it return them; it is the ajax_email.php job to echo the result of the validation class. The ajax_email.php file then echos the $email_status that has been returned by the processor() method. This echo then gets passed back to the callback function of the $.post. You can see that this excerpt is shown here:


, function(data){
         show_email_success(data);

You can see that I created a fictitious method in JavaScript call show_email_succes(data). This method could for example have JQuery code that writes the data variable that will contain the message returned by the php class file to an empty container; say an <em id=‘email_status’></em> were you write the data variables content into this <em>. The <em> would likely be in your pop-up window.

I hope this is clearer for you. You are getting closer :slight_smile:

Steve

Sigh, I have spent the last few hours looking all around trying to find out how to obtain those return statements in the status message/alert log/etc from the PHP script. but I still am trying to learn how to do that in order to build the function’s conditional statements structure.

Hi etidd,

Sorry you’re having trouble :frowning:

The callback function in the JQuery $.post (highlighted in red) have the callback variable ‘data’.


<script='text/javascrit'>
$.post(
    "./libs/email/ajax_email.php"
    , { email_address : ea}
[B][COLOR=#b22222]     , function([/COLOR][COLOR=#0000ff]data[/COLOR][COLOR=#b22222]){[/COLOR][/B]
         show_email_success([B][COLOR=#0000ff]data[/COLOR][/B]);
})
</script>
<?php
echo $[B][COLOR=#0000ff]data[/COLOR][/B];
?>

When the php script you post to (in this example ajax_email.php) echos out a string. The echoed value is then returned to the callback function in the ‘data’ variable.

So you can structure switch logic or if/else to echo a result based on conditions that you define.

It is also possible to echo a serialized string that could be an array or an instance of an object that has state. Although at this point just get the echoing a string working.

Does this help?
Steve

Well, I have to struggle at this if I’m going to learn anything. :eek:

I’m trying to do something like the following:


var ea = $("#go .emailaddressin").val();
var bd = $("#email_form .body_in").val()
$.post(
    "emailtester.php"
    , { email_address : ea}
     , function(data){
         showResult(data);
})


function showResult(data){
	if ($("data:contains("Submission Success")")  //doesn't like this line
}


…but I’m getting a syntax error on the last line. I need to go read about jQuery syntax.

Hi,

Please try


alert(data);

Please put that inside the function(data){ alert(data); } in the $.post method. If you get what you echoed in the called php script. If you get the correct string alerted then you’ve done a full ajax trip and then you can slowly add your other JavaScript and debug if an error occurs

I’m not receiving any pop-up that echoes any string using this jQuery:


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

$(document).ready(function(){
	$("#confirmform").hide()
	});
var ea = $("#go .emailaddressin").val();
var bd = $("#email_form .body_in").val()
$.post(
    "emailtester.php"
    , { email_address : ea }
     , function(data){
		 alert(data);
         showResult(data);
})


function showResult(data){
	//if ($("data:contains("Submission Success")")
}

Ok,

So you’re having problems, so I create a quick and very dirty but working example.

The scripts:

test.js


$(document).ready(function() {
    $('#submit').click(function() {
        var fn = $(".first_name_in").val();
        var ln = $(".last_name_in").val();
        var em = $(".email_address_in").val();
        
        $.post("process_data.php"
          , {first_name : fn
             , last_name : ln
             , email : em
            }
          , function(data){
             $('#status').html(data);
          }); 
     });
});


test_email_form.php


<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, maximum-scale=1.0">
        <title>Email Ajax Test</title>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script type="text/javascript" src="test.js"></script> 
        <style>
            div#submit {
                display: block;
                width: 150px;
                height:20px;
                margin-top: 10px;
                background-color: #ddd;
            }
        </style>
    </head>
    <body>
        <form name='email_form' method='post'>
            First name: <input type="text" class='first_name_in' name="first_name"><br>
            Last name: <input type="text" class='last_name_in'name="last_name"><br>
            Email: <input type="text" class='email_address_in' name="email"><br>
            
        </form>
        <div id='submit'>Send Email</div><br />
        <div id='status'></div>
    </body>
    
</html>

process_data.php


<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$status = 1;
$errors = '<ul>';
if(empty($first_name)){
    $status = 0;
    $errors .= '<li>Sorry you did not enter your first name, try again</li>';
}
if(empty($last_name)){
    $status = 0;
    $errors .= '<li>Sorry you did not enter your last name, try again</li>';
}
if(empty($email)){
    $status = 0;
    $errors .= '<li>Sorry you did not enter your email address, try again</li>';
}
$errors .= '</ul>';


if($status == 1){
    echo 'Your email was sent successfully';
} else {
    echo $errors;
}
?>

I’ve attached these files so you can just download them, rather than copy and pasting.

Put all these files into the same folder on your php server. Then open test_email_form.php. You should see a really ugly looking form with first name, last name, and email, plus a butt ugly submit button.

First try clicking ‘Send Email’ without anything in the form inputs. You should get an unordered list back with 3 error messages.

Second add your first name. Now it will return an unordered list with 2 error messages.

Continue to fill in the fields, when they are all filled and you hit ‘Send Email’ you should see a success message.

This test shows the basics of using a html form, using jQuery ajax to post the inputs to a php file that processes the data. The .php file is set up to return different messages depending on what fields are filled. You can see that we collect the $_POST values and then can evaluate them in php variables. When complete, the php script either echos errors or a success message that gets returned to the AJAX callback function. Then inside the callback function we are setting the HTML of a div to contain the data returned from the php script. You can also see that the page does not reload it uses the AJAX.

I hope this works for you, otherwise you got problems with your php server. I tested this exact same setup and it works as intended.

Please also not that none of this code is elegant in any way and it lacks all security with incoming data. I hammered it together in a few minutes so it is not production acceptable code, but it should illustrate the full cycle that you can build out from.

Regards,
Steve

I’m trying to test out this script. Do I need to set up a new testing server somehow on XAMPP?

I also changed the submit to this:


<input type='submit'/>

If you have a server already you can likely just add these scripts and then reference them off the domain, or download xamp, lamp (Linux), or wamp . I provided the scripts so you could try them to ensure they work. Normally you don’t change anything in a test set of scripts so you can ensure it works, but if you feel you understand it he the more power to you.

If you think you need to download xamp, what server if any server where you using for the scripts in your earlier posts?