#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    7
    Rep Power
    0

    How to add the upload file/photo function into my current form


    Dear all, I am new in Ajax, JQuery, JavaScript. The source code of my current form is shown below. I would like to ask how to add one more field into this form to let the member upload their photo or file.
    For now, when the member click the button, ajax will get the data and send to php. From what I know, ajax send String value to php. So is it possible to add the upload function into this code? Thanks in advance.

    Code:
    <?php
    
    // Ajax calls this NAME CHECK code to execute
    if(isset($_POST["usernamecheck"]))
    {
    	include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; // connect to database
    	$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
    	$sql = "SELECT ID FROM member WHERE Name='$username' LIMIT 1";
        $query = mysqli_query($link, $sql); 
        $uname_check = mysqli_num_rows($query);
        if (strlen($username) < 3 || strlen($username) > 30) {
    	    echo '<strong style="color:#F00;">3 - 30 characters please</strong>';
    	    exit();
        }
    	if (is_numeric($username[0])) {
    	    echo '<strong style="color:#F00;">Username must begin with a letter</strong>';
    	    exit();
        }
        if ($uname_check < 1) {
    	    echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
    	    exit();
        } else {
    	    echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
    	    exit();
        }
    }
    
    // Detect if Ajax send information to database
    if (isset($_POST["fullname"]))
    {
      include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
      
      $fullname = preg_replace('#[^a-z0-9]#i', '', $_POST['fullname']);
      $contact = mysqli_real_escape_string($link, $_POST['contact']);
      $address = mysqli_real_escape_string($link, $_POST['address']);
      $postal = mysqli_real_escape_string($link, $_POST['postal']);
      $gender = mysqli_real_escape_string($link, $_POST['gender']);
      $nationality = mysqli_real_escape_string($link, $_POST['nationality']);
      $birthday = mysqli_real_escape_string($link, $_POST['birthday']);
      $email = mysqli_real_escape_string($link, $_POST['email']);
      
      
      // DUPLICATE DATA CHECKS FOR EMAIL
    	$sql = "SELECT ID FROM member WHERE Email='$email' LIMIT 1";
        $query = mysqli_query($link, $sql); 
    	$emailcheck = mysqli_num_rows($query);
      // FORM DATA ERROR HANDLING
    	if($fullname == "" || $contact == "" || $address == "" || $postal == "" 
    	|| $email == "" || $gender == "" || $nationality == "" || $birthday == "" ){
    		echo "The form submission is missing values.";
            exit();
    	} else if ($emailcheck > 0){ 
            echo "That email address is already in used by others";
            exit();
    	} else if (strlen($fullname) < 3 || strlen($fullname) > 30) {
            echo "Name must be between 3 and 30 characters";
            exit(); 
        } else if (is_numeric($fullname[0])) {
            echo 'Name cannot begin with a number';
            exit();
        } else { 
      // END FORM DATA ERROR HANDLING
    	
      // Add user info into the database table for the main site table
      
        $insertinfo = "INSERT INTO member SET Name='$fullname', Phone='$contact', 
    								  Address='$address', Postalcode='$postal', 
    								  Gender='$gender', Nationality='$nationality', Birthday='$birthday', 
    								  Email='$email', Registerdate = CURDATE(), Logindate = CURDATE()";
    							
      if (!mysqli_query($link, $insertinfo))
      {
    	  $error = 'System error, please try again later.';
    	  include 'error.html.php';
    	  exit();
      }
      
    }
      
      // Email the user their activation link
      $to = "$email";							 
      $from = "admin@abc.com";
      $subject = 'Member Account Activation';
      $message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Thank you for register with us!</title></head>
      <body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
      <a href="URL"><img src="URL" width="36" height="30" alt="yoursitename" style="border:none; float:left;"></a>
      Member Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$fullname.',<br /><br />Click the link below to activate your account when ready:<br /><br />
      <a href="URL/activation.php?id='.$id.'&u='.$fullname.'&e='.$email.'">Click here to activate your account now</a><br /><br />
      Login after successful activation using your:<br />* E-mail Address: <b>'.$email.'</b></div></body></html>';
      $headers = "From: $from\n";
      $headers .= "MIME-Version: 1.0\n";
      $headers .= "Content-type: text/html; charset=iso-8859-1\n";
      mail($to, $subject, $message, $headers);
      echo "signup_success";
      exit();
      }
      exit();
      
    }
    ?>
    		
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">		
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Member Registration</title>
    
    <script src="js/main.js"></script>
    <script src="js/ajax.js"></script>
    <script>
    function restrict(elem){
    	var tf = _(elem);
    	var rx = new RegExp;
    	if(elem == "email"){
    		rx = /[' "]/gi;
    	} else if(elem == "fullname"){
    		rx = /[^a-z0-9]/gi;
    	}
    	tf.value = tf.value.replace(rx, "");
    }
    function emptyElement(x){
    	_(x).innerHTML = "";
    }
    function checkfullname(){
    	var u = _("fullname").value;
    	if(u != ""){
    		_("namestatus").innerHTML = 'checking ...';
    		var ajax = ajaxObj("POST", "member.html.php");
            ajax.onreadystatechange = function() {
    	        if(ajaxReturn(ajax) == true) {
    	            _("namestatus").innerHTML = ajax.responseText;
    	        }
            }
            ajax.send("usernamecheck="+u);
    	}
    }
    function signup(){
    	var u = _("fullname").value;
    	var con = _("contact").value;
    	var add = _("address").value;
    	var pos = _("postal").value;
    	var nat = _("nationality").value;
    	var bir = _("birthday").value;
    	var e = _("email").value;
    	var g = _("gender").value;
    	var statusmessage = _("statusmessage");
    	
    	if(u == "" || e == "" || g == "" || con == "" || add == "" || pos == "" || nat == "" || bir == "" ){
    		statusmessage.innerHTML = "Please fill up all the required fields, thanks";
    	} else {
    		_("signupbtn").style.display = "none";
    		statusmessage.innerHTML = 'please wait ...';
    		var ajax = ajaxObj("POST", "member.html.php");
            ajax.onreadystatechange = function() {
    	        if(ajaxReturn(ajax) == true) 
    			{
    	            if(ajax.responseText == "signup_success")
    				{
    					window.scrollTo(0,0);
    					_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account."; 
    				} 
    				else 
    				{
    				    statusmessage.innerHTML = ajax.responseText;
    					_("signupbtn").style.display = "block";	
    				}
    	        }
            }
            ajax.send("fullname="+u+"&email="+e+"&gender="+g+"&contact="+con+"&address="+add+"&postal="+pos+"&nationality="+nat+"&birthday="+bir); 
    	}
    }
    
    </script>
    </head>
      <body>
       <form name="signupform" id="signupform" onsubmit="return false;">
    	<table width="900" border="1" align="center" cellpadding="1">
    	 <tr>
          <td height="50" colspan="2" align="center">Member Registration</td>
         </tr>
         <tr>
          <td width="220" valign="top"><div align="left">Full Name:</div></td>
          <td width="500" valign="top">
    	  <input id="fullname" type="text" onblur="checkfullname()" onkeyup="restrict('fullname')" maxlength="35">
          <span id="namestatus"></span></td>
         </tr>
         <tr>
          <td valign="top"><div align="left">Contact No:</div></td>
          <td valign="top"><input type="text" id="contact" onfocus="emptyElement('statusmessage')"></td>
         </tr>
    	 <tr>
          <td valign="top"><div align="left">Email:</div></td>
          <td valign="top"><input id="email" type="text" onfocus="emptyElement('statusmessage')" onkeyup="restrict('email')" maxlength="88"></td>
         </tr>
    	 <tr>
          <td valign="top"><div align="left">Address:</div></td>
          <td valign="top"><textarea id="address" rows="3" cols="50" onfocus="emptyElement('statusmessage')"></textarea></td>
         </tr>
    	 <tr>
          <td valign="top"><div align="left">Postal Code:</div></td>
          <td valign="top"><input type="text" id="postal" onfocus="emptyElement('statusmessage')"></td>
         </tr>
         <tr>
          <td valign="top"><div align="left">Gender:</div></td>
          <td valign="top"><input type="radio" name="gender" id="gender" value="Male">Male
                           <input type="radio" name="gender" id="gender" value="Female">Female</td>
         </tr>
    	 <tr>
          <td valign="top"><div align="left">Nationality:</div></td>
          <td valign="top"><input type="text" id="nationality" onfocus="emptyElement('statusmessage')"></td>
         </tr>
    	 <tr>
          <td valign="top"><div align="left">Date of Birth:</div></td>
          <td valign="top"><input type="date" id="birthday" onfocus="emptyElement('statusmessage')"></td>
         </tr>
    	 <tr>
    	  <td valign="top"></td>
    	   <td align="center">
    	     <button id="signupbtn" onclick="signup()">Create Account</button>
    		 <span id="statusmessage"></span>
    	   </td>
    	 </tr>			
        </table>
       </form> 
      </body>
    </html>
    For js/main.js
    Code:
    function _(x) { return document.getElementById(x); }
    For js/ajax.js
    Code:
    function ajaxObj( meth, url ) { var x = new XMLHttpRequest(); x.open( meth, url, true ); x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); return x; } function ajaxReturn(x){ if(x.readyState == 4 && x.status == 200){ return true; } }
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,041
    Rep Power
    119
    You can have multiple uploads using jQuery, if you will do an online search for "jquery ajax multiple file upload"; you will get several results showing you examples/tutorials, on how to do this.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    7
    Rep Power
    0
    Hi, thanks for your reply. I did some research before but I do not know how to implement it together.
    For example, in my current code: <form name="signupform" id="signupform" onsubmit="return false;">. Can I add (method="post" enctype="multipart/form-data" ) inside? Is it correct?
    And this code:
    Code:
    ajax.send("fullname="+u+"&email="+e+"&gender="+g+"&contact="+con+"&address="+add+"&postal="+pos+"&nationality="+nat+"&birthday="+bir);
    is send those string values to php. Is it possible to add some additional variables to send upload file or photo value to php?

    Any suggestion? Thanks.
  6. #4
  7. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,041
    Rep Power
    119
    Originally Posted by AhHong
    Is it possible to add some additional variables to send upload file or photo value to php?
    You should be able to send as many query string variables, as you want to.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    7
    Rep Power
    0
    Hi, thanks for your reply. Are you able to provide basic example? I am still do not know how to integrate them together. Thanks.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    7
    Rep Power
    0
    I have solved the problem myself. Thanks.

IMN logo majestic logo threadwatch logo seochat tools logo