Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Problems Submitting a PHP Form Using a Javascript Call

    Hi, I have a registration form which works fine. I used a script online and edited to my liking.

    I added javascript validation but I'm having problems letting javascript handle the submit function.

    Here's how its setup and it works this way.

    register.php
    PHP Code:
    <?php
    session_start
    ();
    include 
    'core/init.php';

    if(isset(
    $_POST['register']))
    {
      include(
    'class.register.php');

      
    $register = new Register();

      if(
    $register->process())
        
    header('location: registrationsuccessful.php');
      else
        
    $register->show_errors();
    }
    $token $_SESSION['token'] = md5(uniqid(mt_rand(),true));
    ?>

    <form name="accountregisterform" id="accountregisterform" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
     <table width="910">
      <tr><td width="391" align="right">Username:</td><td width="507"><input id="username" onFocus="validateUsername()" onKeyUp="validateUsername()" name="ruser" type="text" style="width:200px; border: solid thin #888"/>&nbsp;<label id="usernameprompt"></label></td></tr>
      <tr><td align="right">Password:</td><td><input id="password" onFocus="validatePassword()" onKeyUp="validatePassword()" name="rpass" type="password" style="width:200px; border: solid thin #888"/>&nbsp;<label id="passwordprompt"></label></td></tr>
      <tr><td>&nbsp;</td></tr>
      <tr><td align="right">Company:</td><td><input id="company" onFocus="validateCompany()" onKeyUp="validateCompany()" name="Company" type="text" style="width:200px; border: solid thin #888"/>&nbsp;<label id="companyprompt"></label></td></tr> </table>
     <input type="hidden" name="token" value="<?php echo $token;?>"/>
     <br />

    <center><input name="register" type="submit" id="accountregisterform2" onclick="validateRegisterForm()" value="Register"/></center>
    </form>


    class.register.php
    PHP Code:
    <?php

    class Login
    {
      private 
    $_ClientID;
      private 
    $_username;
      private 
    $_password;
      private 
    $_passmd5;

      private 
    $_errors;
      private 
    $_access;
      private 
    $_login;
      private 
    $_token;

      public function 
    __construct()
      {
        
    $this->_errors = array();
        
    $this->_login  = isset($_POST['login'])? 0;
        
    $this->_access 0;
        
    $this->_token  $_POST['token'];

        
    $this->_ClientID       0;
        
    $this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username'];
        
    $this->_password = ($this->_login)? $this->filter($_POST['password']) : '';
        
    $this->_passmd5  = ($this->_login)? md5($this->_password) : $_SESSION['password'];
      }

      public function 
    isLoggedIn()
      {
        (
    $this->_login)? $this->verifyPost() : $this->verifySession();

        return 
    $this->_access;
      }

      public function 
    filter($var)
      {
        return 
    preg_replace('/[^a-zA-Z0-9]/','',$var);
      }

      public function 
    verifyPost()
      {
        try
        {
          if(!
    $this->isTokenValid())
             throw new 
    Exception('Invalid Form Submission');

          if(!
    $this->isDataValid())
             throw new 
    Exception('Invalid Form Data');
             
          if(!
    $this->verifyDatabase())
             throw new 
    Exception('Invalid Username/Password');
             
        
    $this->_access 1;
        
    $this->registerSession();
        }
        catch(
    Exception $e)
        {
          
    $this->_errors[] = $e->getMessage();
        }
      }

      public function 
    verifySession()
      {
        if(
    $this->sessionExist() && $this->verifyDatabase())
           
    $this->_access 1;
      }

      public function 
    verifyDatabase()
      {
        
    //Database Connection Data

    include('database/connect.php');

        
    $data mysql_query("SELECT ClientID FROM clients WHERE username = '{$this->_username}' AND password = '{$this->_passmd5}'");

        if(
    mysql_num_rows($data))
          {
            list(
    $this->_ClientID) = @array_values(mysql_fetch_assoc($data));
            return 
    true;
          }
        else
          { return 
    false; }
          
          
    define('data'$data);
          
      }

      public function 
    isDataValid()
      {
        return (
    preg_match('/^[a-zA-Z0-9]{5,12}$/',$this->_username) && preg_match('/^[a-zA-Z0-9]{5,12}$/',$this->_password))? 0;
      }

      public function 
    isTokenValid()
      {
        return (!isset(
    $_SESSION['token']) || $this->_token != $_SESSION['token'])? 1;
      }

      public function 
    registerSession()
      {
        
    $_SESSION['ClientID'] = $this->_ClientID;
        
    $_SESSION['username'] = $this->_username;
        
    $_SESSION['password'] = $this->_passmd5;
      }

      public function 
    sessionExist()
      {
        return (isset(
    $_SESSION['username']) && isset($_SESSION['password']))? 0;
      }

      public function 
    showErrors()
      {
        
        foreach(
    $this->_errors as $key=>$value)
          echo 
    $value."<br>";
      }
    }

    ?>
    The above form is setup so the "action" for the form is action="<?php echo $_SERVER['PHP_SELF'];?>". That code is at the top of the first section and if a condition passes it includes class.register.php which I included. If I add a valid username, password and email address to the form it submits it and brings up the registrationsuccessful.php page.

    That is all good however I need that changed because I have javascript validation I want it to run that first, if its all good then submit the form. Here's the code I have for validation.

    Code:
    function validateRegisterForm()
    {
    	if (!validateUsername() || !validatePassword() || !validateCompany() || !validateContact() || !validateFromSuite() || !validateFromAddress() || !validateFromPostalCode() || !validatePhoneNumber() || !validateEmail() || !validateWebsite())
    	{
    	   // do nothing
    	}
    	else
    	{
    		document.getElementById("accountregisterform").submit();
    	}
    }
    When I try to use this, I move my button outside my form and when I click it it follows the javascript code as it should. When validations good it submits the form however it just reloads the page and throws the data away. It doesn't add it to the database nor does it take me to the registrationsuccesful.php page.

    I know it has something to do with the class.register.php file but have tried everything and can't get anywhere.

    Any ideas would be appreciated.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Nothing to do with php. Moving to javascript forum.

    You have indicated the code functions as expected without the javascript. Therefore your issue lies in the javascript and has nothing to do with class.register.php.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #3
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Code:
    <form name="accountregisterform" id="accountregisterform" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>"> 
       ...
       <input name="register" type="submit" id="accountregisterform2" value="Register"/>
    </form>
    <script type="text/javascript">
    (function(){
         document.getElementById('accountregisterform').onsubmit = function() {
             return validateRegisterForm();
         }
    
         function validateRegisterForm() { 
    	if (!validateUsername() 
                || !validatePassword()
                || !validateCompany()
                || !validateContact()
                || !validateFromSuite()
                || !validateFromAddress()
                || !validateFromPostalCode()
                || !validatePhoneNumber()
                || !validateEmail()
                || !validateWebsite()) {
    	    return false;
    	}
    	else {
    	    return true;
    	}
        }
    })();
    </scrip>
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • Users who have thanked glenngv for this post:

    robsworld78 (03-04-2014)

  • #4
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Amazing, you are good. Thanks so much Glenn!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •