AJAX&PHP form validation doesn't work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • liams
    New Member
    • Dec 2010
    • 26

    AJAX&PHP form validation doesn't work

    Hi, I recently learned how to use AJAX, but I'm having a problem with it. What I'm trying to do is validate a form with PHP, and write the output of the validation in the same page. From the last question I have asked in bytes.com, I was introduced to AJAX(well, I always knew it, but I never used it). So, I wrote the following code accordingly:

    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="/scripts/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="#">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="/scripts/send.php" method="post" 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="submit" value="Send!" onclick="getObject();"/>
    		<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>
    send.php:
    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 = $_POST['recipient'];
    $subject = $_POST['title'];
    $message = $_POST['body'];
    
    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;
    }
    
    ?>
    main.js:
    Code:
    function getObject()
    {
    	var http;
    	
    	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;
    			}	
    		}
    	}
    
    	var email = document.getElementById("recipient");
    	var title = document.getElementById("title");
    	var body = document.getElementById("body");
    	
    	http.open("POST", "send.php", true);
    	http.onreadystatechange = getServer();
    	http.send(null);
    }
    However, it is not working. From what I understand, after checking for flow in each of the files, there's a problem with my JS code. I may be wrong, but from what I tested it seems that it's a problem with the JS.

    What's wrong?? I can't figure it out!

    Thanks! :D
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    there are several problems:

    - index.html #49. whatever getObject() does, after it is done the form will submit, the page reload and thus no JavaScript output visible.

    - main.js #46. a DOM-0 event handler expects a function to be passed, not a function return value. i.e. http.onreadysta techange = getServer;

    Comment

    • liams
      New Member
      • Dec 2010
      • 26

      #3
      Thanks for the reply!

      How could I fix the problem with getObject() so that I will be able to display what I want, the way I want(in the same page). I know this is a simple question, but I'm not very familiar with how AJAX works :P

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        either use a click button or prevent the form from submitting (either by preventing the default action or by explicitly returning false from the event attribute)

        Comment

        • liams
          New Member
          • Dec 2010
          • 26

          #5
          I did this according to this example:


          Why does it stay on the same page for them, and not for me? I would really like to avoid doing such things like preventing the form from submitting.

          Edit:

          I removed the action="/scripts/send.php" from index.html. However, it is still not working. I'm getting no output.

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            Why does it stay on the same page for them, and not for me?
            because they don’t use a submit button.

            Comment

            • liams
              New Member
              • Dec 2010
              • 26

              #7
              Thanks for the reply:D

              Can you give me any example for a code that actually works? I have no idea how to work with event attributes(I only recently started doing websites.. I'm more of a desktop guy).

              Comment

              • Dormilich
                Recognized Expert Expert
                • Aug 2008
                • 8694

                #8
                I have no idea how to work with event attributes(I only recently started doing websites.. I'm more of a desktop guy).
                how much do you want to understand JavaScript Events?

                Can you give me any example for a code that actually works?
                do you have a working page, so that I can check whether the AJAX itself works?

                Comment

                • liams
                  New Member
                  • Dec 2010
                  • 26

                  #9
                  I want to understand JS events as much as I can. My goal is to be good.
                  About the page, I don't use any external hosting. I run it with my Apache server.

                  Comment

                  • Dormilich
                    Recognized Expert Expert
                    • Aug 2008
                    • 8694

                    #10
                    I want to understand JS events as much as I can.
                    this will not be a piece of cake …

                    on another thread I wrote a short summary about Events.

                    you should additionally read some resources:
                    - Peter Paul Koch’s Quirksmode.org (Intro, ToC)
                    - the DOM-Events specifications: DOM-2-Events, DOM-3-Events (there should be something for IE on the MSDN website, too). note that these documents are technical, they exactly describe how events work, i.e. it is not meant as tutorial. still, the introduction section is worth a read to understand the event flow.

                    Comment

                    • liams
                      New Member
                      • Dec 2010
                      • 26

                      #11
                      It's going to take me some time to go over all that. In the meanwhile, I would like to try to fix my current code. I'll deal with staying on the same page later, it's just that I just checked and http.responseTe xt is just nothing! It outputs as " ". I can't fix it =/

                      Comment

                      • Dormilich
                        Recognized Expert Expert
                        • Aug 2008
                        • 8694

                        #12
                        first you have to make sure that you send data to the server. considering the code from post #1 you don‘t send data at all (http.send(null) ;).

                        also, you should make sure your server script responds as planned (temporarly use $_GET instead of $_POST and pass the data in the URL)

                        Comment

                        • liams
                          New Member
                          • Dec 2010
                          • 26

                          #13
                          But I don't even send any data. My PHP code gets the data directly from the form, there's no need to send it. Or is there?? Because in these few lines:
                          Code:
                          $to = $_POST['recipient'];
                          $subject = $_POST['title'];
                          $message = $_POST['body'];
                          These are the only lines where I grab user-generated data from the forms. Why do I need to send any data? I'm only using AJAX to be able to call a PHP validation script, and display it's output on the same page, instead of loading a new page.

                          I'm really confused...=/

                          Comment

                          • Dormilich
                            Recognized Expert Expert
                            • Aug 2008
                            • 8694

                            #14
                            AJAX does not have anything to do with forms. they are completely different things.

                            the PHP script that is called by the XMLHttpRequest object only receives data submitted by that object. where those data originate from does not matter.

                            in your case the regular form submit is rather a fallback should JavaScript be disabled.

                            Comment

                            • liams
                              New Member
                              • Dec 2010
                              • 26

                              #15
                              Well, I tried changing my code but still no luck!

                              main.js changed:
                              Code:
                              function getObject(f)
                              {
                              	var http;
                              	var url = "send.php";
                              	var email = f.elements['recipient'];
                              	var subject = f.elements['title'];
                              	var body = f.elements['body'];
                              	var parameters = "e=" + email + "&s=" + subject + "&b=" + body;
                              and
                              Code:
                              http.open("GET", url+"?"+parameters, true);
                              in send.php
                              Code:
                              $to = $_GET['e'];
                              $subject = $_GET['s'];
                              $message = $_GET['b'];

                              and in index.html
                              Code:
                              <form name="sendmail" action="" method="" class="sender">
                              Code:
                              <input name="submit" type="submit" value="Send!" onclick="getObject(this.form);"/>

                              Doesn't work at all.. and I'm getting a totally different url!
                              index.html?reci pient=s&title=d &body=d&submit= Send!

                              Ok, I'm gonna shoot myself...

                              Comment

                              Working...