Announcement

Collapse
No announcement yet.

JQuery PHP Forms for people with no Javascript

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • JQuery PHP Forms for people with no Javascript

    There is one problem I have come across with a lot of websites using JQuery / Ajax to submit forms. If I decide I want to browse without Javascript enabled (Not that I do), there is nothing I can do but leave most sites because they do not cater for viewers that are not using Javascript. Now I understand that if there are any people at all that browse the internet without Javascript, It isn't going to be many. I still feel we should work towards creating websites and applications that can be used with or without Javascript.

    Here is my proposal - What if there was an easy was to create a page that can submit a form using Ajax / Jquery if the viewer is using Javascript but also submit the form if not, without writing the PHP to process the information twice. A simple way I have found to do this is to create an ajaxHandler class. For this example / tutorial I will be using a dummy login form.

    Ok, so first we need to create our form. I have called my file login.php. Doing this we need to add both the name and ID attributes for the input fields, and we also need to make note of the names because our Ajax / JQuery is going to submit the same post names -

    HTML Code:
    <html>
    	<head>
    		<title>My JQuery Login</title>
    		<script language="Javascript" src="scripts/jquery.js"></script>
    		<script language="Javascript" src="scripts/login.js"></script>
    	</head>
    	<body>
    		<form action="" method="post">
    			<p>Username: <input type="text" name="usernameTxt" id="usernameTxt" /></p>
    			<p>Password: <input type="password" name="passwordTxt" id="passwordTxt" /></p>
    			<input type="submit" name="loginButton" id="loginButton" value="Login!" />
    		</form>
    	</body>
    </html>
    You will notice that I have also included the JQuery Javascript file, and for now what is a blank Javascript file called login.js. Now I shall move on too our ajaxHanler.php class.

    PHP Code:
    <?php

    // Because this example is for a login form, we need to check if the
    // session has been started already just in case we include this file
    // into a file that has already started the session
    if(session_id() == ""){
        
    session_start();
    }

    //Start of the class
    class ajaxHandler {
        
        
    //Array to store all valid functions that can be called via Ajax / JQuery
        
    private $validFuncs = array("userLogin");
        
        
    //Variable to store the data to be returned
        
    private $returnData null;
        
        
    //Constructer that checks that a valid function has been submitted
        
    public function __construct($postData){
            if(!isset(
    $postData['func']) || !in_array($postData['func'], $this->validFuncs)){
                
    $this->returnData "Unfortunately we have encountered an error!";
            }else {
                
    //If it was a valid function call that function passing the post data
                
    $this->$postData['func']($postData);
            }
        }
        
        
    //Destruter that checks if any data needs returning if so return it to jquery
        
    public function __destruct(){
            if(
    $this->returnData != null){
                echo 
    $this->returnData;
            }
        }
        
        
    //This function is only called if a user does not have Javascript Enabled
        //It returns the data to the file its included. Afterwards it nullifies
        //The value to stop the destructer echoing it at the end of the file
        
    public function getReturnData(){
            if(
    $this->returnData != null){
                
                
    $data $this->returnData;
                
    $this->returnData null;
                
                return 
    $data;
                
            }else {
                
                
    //If there is not return data- return false;
                
    return false;
            }
        }
        
        
    //This is a function that will be called by the constructor based upon what function
        //is sent by either jquery or defined by the file
        
    private function userLogin($postData){
            
            
    //Here goes you general login processing stuff
            //Ive done a dummy for this example.
            
    $username $postData['usernameTxt'];
            
    $password $postData['passwordTxt'];
            
            if(
    $username == "Chuckymong" && $password == "myPassword"){
                
    $this->returnData "You have successfully logged in!";
            }else {
                
    $this->returnData "Invalid Username or Password!";
            }
        }
        
        
    //END OF CLASS

    //We create an instance of class here so when JQuery submits post data it is passed
    //Straight to the constructer, then processed and echoed back.
    $ajaxHandler = new ajaxHandler($_POST);

    ?>
    Now that might look like a lot of code for something so simple but, now we have written it all we need to do is add 1 function for everything we want processed using data from Ajax / Jquery or a standard form. Do not forget to add the name of the functions you add to the array of valid functions.

    Now we can create our JQuery to submit the form. This is going into the login.js file in the scripts directory that I included into the login.php file we created before. We are going to post the data directly to our ajaxHandler.php file. Here is my JQuery to submit the form -

    Code:
    $(document).ready(function(){
    	
    	$('#loginButton').click(function(){
    	
    		var username = $('#usernameTxt').val();
    		var password = $('#passwordTxt').val();
    		
    		if(username == "" || password == ""){
    			alert("You need to fill in a username and password!");
    		}else {
    			$.post('ajaxHandler.php', {func:'userLogin',usernameTxt:username,passwordTxt:password}, function(result){
    				
    				if(result == "true"){
    					alert("You have successfully logged into your account!");
    				}else {
    					alert(result);
    				}
    				
    			});
    		}
    		return false; //Note: We return false at the end.
    	});
    });
    We return false at the end of the function so that if the browser has Javascript enabled it stops the form from submitting. Now we are almost done. All that's left to do is modify our login.php file to include the ajaxHandler if javascript is not enabled. At first this sounds like a big task, but because the form only submits to itself if javascript isn't enabled, we know that if there is any post data set, it means the viewer has not got Javascript enabled. The only things we need to do are -
    • Check if there is any post data
    • If there is we have to set our "func" post data manually
    • And include the ajaxHandler file
    The reason we must set our "func" post data manually is because this is set by the Javascript. So here is the modified file -

    PHP Code:
    <?php

    //Check if the form was submitted
    if(isset($_POST['loginButton'])){
        
        
    //If it was set the func value manually
        
    $_POST['func'] = "userLogin";
        
        
    //Include the ajaxHandler which will automatically process the data
        
    include "ajaxHandler.php";
    }

    ?>
    <html>
        <head>
            <title>My Jquery Login</title>
            <script language="Javascript" src="scripts/jquery.js"></script>
            <script language="Javascript" src="scripts/login.js"></script>
        </head>
        <body>
            <?php
            
            
    //If the ajaxHandler variable is set it means we have recieved post data
            //And it has been processed by the same function it would of if it was
            //Sent using JQery / Ajax and the result is ready
            
    if(isset($ajaxHandler)){
                
                
    //Format and echo the result to your personal preference
                
    echo "<b>".$ajaxHandler->getReturnData()."</b>";
                    
            }
            
            
    ?>
            <form action="" method="post">
                <p>Username: <input type="text" name="usernameTxt" id="usernameTxt" /></p>
                <p>Password: <input type="password" name="passwordTxt" id="passwordTxt" /></p>
                <input type="submit" name="loginButton" id="loginButton" value="Login!" />
            </form>
        </body>
    </html>
    As you can clearly see from above the Post data is getting processed by the exact same function that it would of if it were by JQuery.

    I understand that not everybody shares my opinion about supporting those web users that do not use Javascript but for anybody who does, I hope this may be of use to you.

    Marcus.
    Attached Files

    If your thread has been solved by a member of HTMLForums or if you managed to solve the problem yourself, could you please mark the thread as Resolved.
Working...
X