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

Yep, that sure works, even though it only checks if it the field is empty!

Now, do I need to redo my form to have a div submit instead of a

<input type='submit'/>

and also leave the action attribute of the form unspecified (I know this is a no-no in validation)?

Well, I’ve tried to replicate this same code for my current problem, except that I still have a traditional submit input and not a div. When I click the submit button, the page repositions the scroll bar at the top as if the page has been refreshed (not what I want), and I also don’t see any posted results in a div I have called status, which is at the bottom of my html file.

JQuery:


$(document).ready(function(){
	$("#emailsubmit").click(function(){
		var ea = $("#go .emailaddressin").val();
		
		$.post(
    		"emailtester.php"
    		, { email_address : ea }
     		, function(data){
		 		alert(data);
         		showResult(data);
				$('#status').html(data);
			});
	});
});

emailtester.php


<?php
	require_once('checkfirstsub.php');
	$status = 1;
	$errors = "<ul>";

	if($_POST['go']){
  		$email = htmlentities($_POST['go']);
		echo $errors . '<li>Submission Success</li></ul>';
	} else {
		$status = 0; 
		echo $errors . '<li>Submission Failure - Empty Box</li></ul>';
	}

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

	echo $email_status;
?>

checkfirstsub.php


<?php
    class ProcessEmail
    {
		protected $email_address;
		
        public function processor($email)
        {
	    $this->email_address = $email;
		$errors = '<ul>';
		$status = 1;

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

form markup:


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

       <!--
        2nd form markup here
       -->
     
      <div id="status">
  </div> 

Ok, so I modified the test stuff I sent you earlier. Again this was a real quick refinement so it sorely lacks in security protection and good object design or assessibility design.

What I wanted to illustrate to you is:

  • the use of an Object in the data processing file
  • the jQuery function for submit
  • the ability for this to have an action and work if JavaScript is disabled.

I didn’t have time to pack it in a ZIP file, so this time you’ll have to copy it.

test.js


$(document).ready(function() {
    [COLOR=#ff0000]$("form").submit(function(event) {[/COLOR]
[COLOR=#ff0000]        event.preventDefault();[/COLOR]
        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
[COLOR=#ff0000]             , ajax : '1'[/COLOR]
            }
          , function(data){
             $('#status').html(data);
          }); 
     });
});

[B]
test_email_form.html

[/B]


<!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' action='process_data.php'>
            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>
            [COLOR=#ff0000]<input type="submit" name="send" value="Submit" />[/COLOR]
        </form>
        
        <div id='status'></div>
    </body>
    
</html>

and

[B]process_data.php

[/B]


<?php
$ajax = $_POST['ajax'];
$first_name = htmlentities($_POST['first_name']);
$last_name = htmlentities($_POST['last_name']);
$email = htmlentities($_POST['email']);


$o_Validate = new Validate($first_name, $last_name, $email);
if($ajax == 1){
    echo $o_Validate->testForErrors();
} else {
    $errors = $o_Validate->testForErrors();
?>
<!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' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
            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>
            <input type="submit" name="send" value="Submit" />
        </form>
        
        <h2>Message(s)</h2>
        <?php echo $errors; ?>
    </body>
    
</html>
<?php
}
?>
<?php 


class Validate {
    protected $first_name;
    protected $last_name;
    protected $email;
    
    function __construct($first_name, $last_name, $email){
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->email = $email;
        
    }
    public function testForErrors(){
        $status = 1;
        $errors = '<ul>';
        if(empty($this->first_name)){
            $status = 0;
            $errors .= '<li>Sorry you did not enter your first name, try again</li>';
        }
        if(empty($this->last_name)){
            $status = 0;
            $errors .= '<li>Sorry you did not enter your last name, try again</li>';
        }
        if(empty($this->email)){
            $status = 0;
            $errors .= '<li>Sorry you did not enter your email address, try again</li>';
        }
        $errors .= '</ul>';
    
        if($status == 1){
            return 'Your email was sent successfully';
        } else {
            return $errors;
        }
    }
}
?>

You can see the most extensive changes in the process_data.php file. Please note the extra ajax JavaScript variable that is passed to this .php page. This is used to decide if the request was initiated by the AJAX object or if it didn’t (JavaScript turned off or device incapable of loading JavaScript).

Again, you can call as many objects and manipulate whatever data you want in the process_data.php page. Even if you need to echo an Array you can

myarray = array(one, two, three);

echo implode(“,”, myarray); /This will echo a string one, two, three that you can interpret in a JavaScript array/

Sorry for the quickness.

Steve

Here, I tried something similar to that. When I click the submit button, nothing happens on the page.

emailbox.js


$(document).ready(function(){
	$("#emailbox").submit(function(event){
		event.preventDefault();
		var ea = $("#go .emailaddressin").val();
		
		$.post(
    		"emailtester.php"
    		, { email_address : ea
			   , ajax : 1 }
     		, function(data){
				$('#status').html(data);
				showResult(data);
			});
	});
});

emailtester.php


<?php
	require_once('checkfirstsub.php');
	$status = 1;
	$ajax = $_POST['ajax'];
	$messages = " ";

	if($_POST['go']){
  		$email = htmlentities($_POST['go']);
		$messages = '<ul><li>Submission Success</li></ul>';
	} else {
		$status = 0;
		$messages = '<ul><li>Submission Failure - Empty Box</li></ul>';
	}

	$obj_PE = new ProcessEmail();
	if ($ajax == 1)
		$messages = $obj_PE -> processor($email);
	else {
		$messages = $obj_PE -> processor($email);
	}
?>
<!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="viewport" content="width=device-width, maximum-scale=1.0" />
    <title>Sign Up for the Mailing List at World Review Group</title>
    <script type="text/javascript" src="emailbox.js"></script>
    <script type="text/javascript" src="Scripts/jQuery.js"></script>
</head>
<body>
	  <form id="emailbox" name="form1" method="post" action=<?php $_SERVER['PHP_SELF']; ?>>
        <div>
          <input type="text" name="emailaddress" id="go" class="emailaddressin" value="your e-mail" onclick="input_focus(this)"  onblur="input_reset(this)" maxlength="60"/>
          <input type="submit" id="emailsubmit" value="Join" />
        </div>
      </form>
      <h2>Message(s)</h2>
      <?php echo $messages; ?>
</body>
</html>

checkfirstsub.php


<?php
    class ProcessEmail
    {
		protected $email_address;
		
        public function processor($email)
        {
	    $this -> email_address = $email;
		$status = 1;

            if ($email != "your e-mail"){
                    if (isItAValidEmail($email))
                    {
                        return '<ul><li>Submission Successful</li></ul>';
                    } else {
                        return '<ul><li>Submission Failure- Invalid E-mail</li></ul>';
						$status = 0;
                    }
	    	} else {
				return '<ul><li>Submission Failure- Default Value in Box</li></ul>';
				$status = 0;
	    	}
        }

        protected function isItAValidEmail()
        {
            if (filter_var($this->email, FILTER_VALIDATE_EMAIL))
                return true;
            else
                return false;
        }
    }
?>

index.html (main form on the home page)


<form id="emailbox" name="form1" method="post" action="Scripts/emailtester.php">
        <div>
          <input type="text" name="emailaddress" id="go" class="emailaddressin" value="your e-mail" onclick="input_focus(this)"  onblur="input_reset(this)" maxlength="60"/>
          <input type="submit" id="emailsubmit" value="Join" />
        </div>
      </form>

Hi,

Off the bat I can see that your emailtester.php seems wrong to me. Here is what I think it needs to be:

emailtester.php


<?php
    require_once('checkfirstsub.php');
    $status = 1;
    $ajax = $_POST['ajax'];
    $messages = " ";

    if($_POST['go']){
          $email = htmlentities($_POST['go']);
        $messages = '<ul><li>Submission Success</li></ul>';
    } else {
        $status = 0; 
        $messages = '<ul><li>Submission Failure - Empty Box</li></ul>';
    }

    $obj_PE = new ProcessEmail();
    if ($ajax == 1)
      [COLOR=#b22222]  /* this is the code that echo the message that triggers the JavaScript post callback, This php code is called in a separate email form (not the one listed below in the else statement. For exampel this ajax code is running in a test_email_form.html page */[/COLOR]
        echo $obj_PE -> processor($email);
    else {
       [COLOR=#b22222] /* This is the code that is run if JavaScript is turned off or is not supported */[/COLOR]
        $messages = $obj_PE -> processor($email);
[COLOR=#b22222]// removed else bracket[/COLOR]
?>
<!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="viewport" content="width=device-width, maximum-scale=1.0" />
    <title>Sign Up for the Mailing List at World Review Group</title>
    <script type="text/javascript" src="emailbox.js"></script>
    <script type="text/javascript" src="Scripts/jQuery.js"></script>
</head>
<body>
      <form id="emailbox" name="form1" method="post" action=<?php $_SERVER['PHP_SELF']; ?>>
        <div>
          <input type="text" name="emailaddress" id="go" class="emailaddressin" value="your e-mail" onclick="input_focus(this)"  onblur="input_reset(this)" maxlength="60"/>
          <input type="submit" id="emailsubmit" value="Join" />
        </div>
      </form>
      <h2>Message(s)</h2>
      <?php echo $messages; ?>
</body>
</html>
[COLOR=#b22222]<?php
}  // Added the Else end bracket for the non-AJAX 'traditional post else statement
?>[/COLOR]

Also don’t forget to put a target for the AJAX callback data to be displayed like:

home.html


<!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="emailbox.js"></script>
         <style>
            div#submit {
                display: block;
                width: 150px;
                height:20px;
                margin-top: 10px;
                background-color: #ddd;
            }
        </style>
    </head>
    <body>
       <form id="emailbox" name="form1" method="post" action="Scripts/emailtester.php">
            <div>
                <input type="text" name="emailaddress" id="go" class="emailaddressin" value="your e-mail" onclick="input_focus(this)"  onblur="input_reset(this)" maxlength="60"/>
                <input type="submit" id="emailsubmit" value="Join" />
           </div>
       </form>
      [COLOR=#b22222] <div id='status'></div> <!-- gets the AJAX callback data -->[/COLOR]
    </body>
  </html>

Well, I made those necessary corrections. I also saw I forgot quotes in the action form around $_SERVER[‘PHP_SELF’];

It’s not doing anything still.

Oh, and I am putting the site to my testing server each time before I test the changes.

I made these corrections and also found that I left quotes off of the action attribute around $_SERVER[‘PHP_SELF’];, but it still does nothing when I attempt to use it.

I’m updating/re-putting the files to the testing server each time I try a new solution.

OOPS, re-posted on accident. Sorry.