AJAX&PHP form validation doesn't work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #16
    index.html?reci pient=s&title=d &body=d&submit= Send!
    this is what you get from submitting the form. try alerting the parameter variable from above. (ah, yes, and change the submit button in a click button to prevent the form submission)

    PS. AJAX works behind the lines, you normally see nothing from AJAX itself.

    Comment

    • liams
      New Member
      • Dec 2010
      • 26

      #17
      Now after changing it to type="button" I'm getting a wonderful Not Found error. But hey, at least I'm getting it on the same page, and in green too.
      Not Found

      The requested URL /send.php was not found on this server.

      Amazingly enough, send.php is on the same folder main.js is. Not same as index.html though. Perhaps this causes the problem?

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #18
        Perhaps this causes the problem?
        let me answer very short—yes.

        Comment

        • liams
          New Member
          • Dec 2010
          • 26

          #19
          I moved all files to the same directory. Paths are correct now, and it seems that the "error" <span> does change but there's no text. Only a new line is inserted into the "error" <span>. I seriously have no idea what's the problem. And I mean..really... .It should work! Also, the URL stays the same as if the parameters and GET are ignored completely!

          FULL CODE:

          index.html
          Code:
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
          
          <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
          <head>
          
          <title> Unimail </title>
          
          <script type="text/javascript" src="main.js"></script>
          <link rel="shortcut icon" href="/images/favicon.ico" />
          <link rel="stylesheet" type="text/css" href="/styles/main.css" />
          
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta property="og:description" content="Free one-time use email" />
          <meta property="og:title" content="Unimail email service" />
          <meta name="author" content="Unimail" />
          <meta property="og:site_name" content="Unimail" />
          
          </head>
          
          <body>
          
          <div id="wrapper">
          <div id="top">
          	<div class="header">
          		<img src="/images/email_logo4.jpg" alt="Unimail" />
          	</div>
          	<div class="navig">
          		<ul class="navbar">
          			<li><a href="http://localhost/index.html"><span>Home</span></a></li>
          			<li><a href="http://localhost/about.html">About us</a></li>
          			<li><a href="#">FAQ</a></li>
          			<li><a href="#">Contact</a></li>
          			<li><a href="#">Other services</a></li>
          		</ul>
          	</div>
          </div>
          
          <div id="body">
          	<br />
          	<p> Hello! Welcome to Unimail! With Unimail, you can send emails without registering. No inbox, no pre-chosen address, no name. One-time email! </p>
          	
          	<br /><br />
          	
          	<form name="sendmail" action="" method="" class="sender">
          	
          		<p>Recipient's address </p> <input name="recipient" type="text" id="recipient" /><br />
          		<p> Title </p><input name="title" type="text" id="title" />
          		<p> Body </p><textarea rows="15" cols="65" name="body" id="body" ></textarea><br />
          		<input name="submit" type="button" value="Send!" onclick="getObject(this.form);"/>
          		<span id="error"> </span>
          		 
          	</form>
          	<p> Remember! You will not be able to receive any reply! </p>
          </div>
          <div id="footer">
          	<p> This site was created for occasional emailing. Please do not attempt to use this site to spam emails. </p>
          </div>
          
          </div>
          
          </body>
          
          </html>
          Code:
          function getObject(f)
          {
          	var http;
          	var url = "send.php";
          	var email = f.elements['recipient'].value;
          	var subject = f.elements['title'].value;
          	var body = f.elements['body'].value;
          	var parameters = "e=" + email + "&s=" + subject + "&b=" + body;
          
          	try
          	{
          		http = new XMLHttpRequest();
          	}
          		
          	catch(e)
          	{
          		try
          		{
          			http = new ActiveXObject("Msxml2.XMLHTTP");
          		}
          		
          		catch(e)
          		{
          			http = new ActiveXObject("Microsoft.XMLHTTP");
          		}
          	}
          	
          	function getServer()
          	{
          		if (http.readyState == 4)
          		{
          			if (http.responseText.match("Error") == "Error")
          			{
          				document.getElementById("error").style.color = "red";
          				document.getElementById("error").innerHTML = "  " + http.responseText;
          			}
          		
          			else
          			{
          				document.getElementById("error").style.color = "green";
          				document.getElementById("error").innerHTML = "  " + http.responseText;
          			}	
          		}
          	}
          
          	http.open("GET", url+"?"+parameters, true);
          	http.onreadystatechange = getServer;
          	http.send(null);
          }
          Code:
          <?php
           
          require_once('class.phpgmailer.php');
          
          $emailRep = "";
          $titleRep = "";
          $bodyRep = "";
           
          function verifyEmail($email)
          {
              if (filter_var($email, FILTER_VALIDATE_EMAIL) == true)
              {
                  return true;
              }
           
              $emailRep = "Error: Invalid email address!";
          }
           
          function verifyTitle($title)
          {
              if (strlen($title) > 0)
              {
                  return true;
              }
           
              $titleRep = "Error: Empty titles are not allowed!";
          }
           
          function verifyBody($body)
          {
              if (strlen($body) > 19)
              {
                  return true;
              }
           
              $bodyRep = "Error: Your email must consist of at least 20 character!";
          }
          
          $to = $_GET['e'];
          $subject = $_GET['s'];
          $message = $_GET['b'];
          
          if (verifyEmail($to) && verifyTitle($subject) && verifyBody($message))
          {
              $mail = new PHPGMailer();
              $mail->Username = 'unimail.auto@gmail.com';
              $mail->Password = '*******************';
              $mail->From = 'unimail.auto@gmail.com';
              $mail->FromName = 'Unimail';
              $mail->Subject = $subject;
              $mail->AddAddress($to);
              $mail->Body = $message;
              $mail->Send();
           
              echo "Message sent!";
          }
           
          else
          {
              echo $emailRep . "<br />" . $titleRep . "<br />" . $bodyRep;
          }
           
          ?>

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #20
            on line #45 (JavaScript) insert: alert(parameter s);, what does this give?

            Comment

            • liams
              New Member
              • Dec 2010
              • 26

              #21
              When I wrote A as the email, B as the subject, and C as the title in my form it gave:

              e=A&s=B&b=C

              Comment

              • Dormilich
                Recognized Expert Expert
                • Aug 2008
                • 8694

                #22
                your PHP needs some debugging then.

                first, use an email address, otherwise your email check will fail for sure.

                second, PHP is not as sloppy with its variable’s scope as JavaScript. the assignments on lines #16, #26 & #36 do not change anything (because they are local to the function).

                what I consider the best solution is to control the programme flow. therefore the check functions have to break the programme flow if the condition is not met.
                Code:
                function verifyTitle($text)
                {
                    # abort if the text length is zero
                    if (strlen(trim($text)) == 0)
                    {
                        throw new LengthException("Empty titles are not allowed!");
                    }
                    # further input validation/sanitising
                    return $text;
                }
                the other check functions must be coded appropriately. (use an UnexpectedValue Exception() for verifyEmail() and LengthException () for verifyBody()).

                putting it together.
                Code:
                # I left off the function definitions here
                
                # start controlling the flow
                try
                {
                    $title = verifyTitle($_GET['s']);
                    $body  = verifyBody($_GET['b']);
                    $email = verifyEmail($_GET['e']);
                    $mail  = new PHPGMailer();
                    // etc.
                }
                # collect any errors and output the error message
                catch (Exception $e)
                {
                    echo $e->getMessage();
                }
                # end of flow control
                should at any place fire the Exception, all code until the next catch() block is not executed. inside the catch() block you have full access to the error.

                Comment

                • liams
                  New Member
                  • Dec 2010
                  • 26

                  #23
                  Awesome!! Thanks!! it works now!! Just one more question!

                  It only displays one of the exceptions caught. If more than 1 is caught, how do I display them correctly?


                  Thanks !!! =D

                  Comment

                  • Dormilich
                    Recognized Expert Expert
                    • Aug 2008
                    • 8694

                    #24
                    that doesn’t happen. Exceptions are thrown once at a time.

                    all code until the next catch() block is not executed

                    Comment

                    • liams
                      New Member
                      • Dec 2010
                      • 26

                      #25
                      So what happens if a bad title and body is input? I want to display two error messages. How do I do this?

                      Comment

                      • Dormilich
                        Recognized Expert Expert
                        • Aug 2008
                        • 8694

                        #26
                        you can’t, because checkBody() will not be executed after the previous check failed. this may seem inconvenient for you, but it makes sense for your PHP programme. it must be cancelled when an error occurs. the presence of any further errors is irrelevant at this point.

                        of course you can create a script that only checks the validaty of each input, but that’s something you should implement in JavaScript.

                        Comment

                        • liams
                          New Member
                          • Dec 2010
                          • 26

                          #27
                          Alright! Thanks!!

                          Comment

                          Working...