By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,934 Members | 1,692 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,934 IT Pros & Developers. It's quick & easy.

AJAX&PHP form validation doesn't work

P: 26
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:
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2.  
  3. <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5.  
  6. <title> Unimail </title>
  7.  
  8. <script type="text/javascript" src="/scripts/main.js"></script>
  9. <link rel="shortcut icon" href="/images/favicon.ico" />
  10. <link rel="stylesheet" type="text/css" href="/styles/main.css" />
  11.  
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  13. <meta property="og:description" content="Free one-time use email" />
  14. <meta property="og:title" content="Unimail email service" />
  15. <meta name="author" content="Unimail" />
  16. <meta property="og:site_name" content="Unimail" />
  17.  
  18. </head>
  19.  
  20. <body>
  21.  
  22. <div id="wrapper">
  23. <div id="top">
  24.     <div class="header">
  25.         <img src="/images/email_logo4.jpg" alt="Unimail" />
  26.     </div>
  27.     <div class="navig">
  28.         <ul class="navbar">
  29.             <li><a href="http://localhost/index.html"><span>Home</span></a></li>
  30.             <li><a href="#">About us</a></li>
  31.             <li><a href="#">FAQ</a></li>
  32.             <li><a href="#">Contact</a></li>
  33.             <li><a href="#">Other services</a></li>
  34.         </ul>
  35.     </div>
  36. </div>
  37.  
  38. <div id="body">
  39.     <br />
  40.     <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>
  41.  
  42.     <br /><br />
  43.  
  44.     <form name="sendmail" action="/scripts/send.php" method="post" class="sender">
  45.  
  46.         <p>Recipient's address </p> <input name="recipient" type="text" id="recipient" /><br />
  47.         <p> Title </p><input name="title" type="text" id="title" />
  48.         <p> Body </p><textarea rows="15" cols="65" name="body" id="body" ></textarea><br />
  49.         <input name="submit" type="submit" value="Send!" onclick="getObject();"/>
  50.         <span id="error"> </span>
  51.  
  52.     </form>
  53.     <p> Remember! You will not be able to receive any reply! </p>
  54. </div>
  55. <div id="footer">
  56.     <p> This site was created for occasional emailing. Please do not attempt to use this site to spam emails. </p>
  57. </div>
  58.  
  59. </div>
  60.  
  61. </body>
  62.  
  63. </html>
  64.  
send.php:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. require_once('class.phpgmailer.php');
  4.  
  5. $emailRep = "";
  6. $titleRep = "";
  7. $bodyRep = "";
  8.  
  9. function verifyEmail($email)
  10. {
  11.     if (filter_var($email, FILTER_VALIDATE_EMAIL) == true)
  12.     {
  13.         return true;
  14.     }
  15.  
  16.     $emailRep = "Error: Invalid email address!";
  17. }
  18.  
  19. function verifyTitle($title)
  20. {
  21.     if (strlen($title) > 0)
  22.     {
  23.         return true;
  24.     }
  25.  
  26.     $titleRep = "Error: Empty titles are not allowed!";
  27. }
  28.  
  29. function verifyBody($body)
  30. {
  31.     if (strlen($body) > 19)
  32.     {
  33.         return true;
  34.     }
  35.  
  36.     $bodyRep = "Error: Your email must consist of at least 20 character!";
  37. }
  38.  
  39. $to = $_POST['recipient'];
  40. $subject = $_POST['title'];
  41. $message = $_POST['body'];
  42.  
  43. if (verifyEmail($to) && verifyTitle($subject) && verifyBody($message))
  44. {
  45.     $mail = new PHPGMailer();
  46.     $mail->Username = 'unimail.auto@gmail.com';
  47.     $mail->Password = '***********';
  48.     $mail->From = 'unimail.auto@gmail.com';
  49.     $mail->FromName = 'Unimail';
  50.     $mail->Subject = $subject;
  51.     $mail->AddAddress($to);
  52.     $mail->Body = $message;
  53.     $mail->Send();
  54.  
  55.     echo "Message sent!";
  56. }
  57.  
  58. else
  59. {
  60.     echo $emailRep . "<br />" . $titleRep . "<br />" . $bodyRep;
  61. }
  62.  
  63. ?>
  64.  
main.js:
Expand|Select|Wrap|Line Numbers
  1. function getObject()
  2. {
  3.     var http;
  4.  
  5.     try
  6.     {
  7.         http = new XMLHttpRequest();
  8.     }
  9.  
  10.     catch(e)
  11.     {
  12.         try
  13.         {
  14.             http = new ActiveXObject("Msxml2.XMLHTTP");
  15.         }
  16.  
  17.         catch(e)
  18.         {
  19.             http = new ActiveXObject("Microsoft.XMLHTTP");
  20.         }
  21.     }
  22.  
  23.     function getServer()
  24.     {
  25.         if (http.readyState == 4)
  26.         {    
  27.             if (http.responseText.match("Error") == "Error")
  28.             {
  29.                 document.getElementById("error").style.color = "red";
  30.                 document.getElementById("error").innerHTML = "  " + http.responseText;
  31.             }
  32.  
  33.             else
  34.             {
  35.                 document.getElementById("error").style.color = "green";
  36.                 document.getElementById("error").innerHTML = "  " + http.responseText;
  37.             }    
  38.         }
  39.     }
  40.  
  41.     var email = document.getElementById("recipient");
  42.     var title = document.getElementById("title");
  43.     var body = document.getElementById("body");
  44.  
  45.     http.open("POST", "send.php", true);
  46.     http.onreadystatechange = getServer();
  47.     http.send(null);
  48. }
  49.  
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
Dec 12 '10 #1

✓ answered by Dormilich

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.
Expand|Select|Wrap|Line Numbers
  1. function verifyTitle($text)
  2. {
  3.     # abort if the text length is zero
  4.     if (strlen(trim($text)) == 0)
  5.     {
  6.         throw new LengthException("Empty titles are not allowed!");
  7.     }
  8.     # further input validation/sanitising
  9.     return $text;
  10. }
the other check functions must be coded appropriately. (use an UnexpectedValueException() for verifyEmail() and LengthException() for verifyBody()).

putting it together.
Expand|Select|Wrap|Line Numbers
  1. # I left off the function definitions here
  2.  
  3. # start controlling the flow
  4. try
  5. {
  6.     $title = verifyTitle($_GET['s']);
  7.     $body  = verifyBody($_GET['b']);
  8.     $email = verifyEmail($_GET['e']);
  9.     $mail  = new PHPGMailer();
  10.     // etc.
  11. }
  12. # collect any errors and output the error message
  13. catch (Exception $e)
  14. {
  15.     echo $e->getMessage();
  16. }
  17. # 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.

Share this Question
Share on Google+
26 Replies


Dormilich
Expert Mod 5K+
P: 8,639
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.onreadystatechange = getServer;
Dec 12 '10 #2

P: 26
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
Dec 12 '10 #3

Dormilich
Expert Mod 5K+
P: 8,639
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)
Dec 12 '10 #4

P: 26
I did this according to this example:
http://www.tizag.com/ajaxTutorial/aj...ttprequest.php

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.
Dec 13 '10 #5

Dormilich
Expert Mod 5K+
P: 8,639
Why does it stay on the same page for them, and not for me?
because they don’t use a submit button.
Dec 13 '10 #6

P: 26
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).
Dec 13 '10 #7

Dormilich
Expert Mod 5K+
P: 8,639
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?
Dec 13 '10 #8

P: 26
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.
Dec 13 '10 #9

Dormilich
Expert Mod 5K+
P: 8,639
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.
Dec 13 '10 #10

P: 26
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.responseText is just nothing! It outputs as " ". I can't fix it =/
Dec 13 '10 #11

Dormilich
Expert Mod 5K+
P: 8,639
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)
Dec 13 '10 #12

P: 26
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:
Expand|Select|Wrap|Line Numbers
  1. $to = $_POST['recipient'];
  2. $subject = $_POST['title'];
  3. $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...=/
Dec 13 '10 #13

Dormilich
Expert Mod 5K+
P: 8,639
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.
Dec 13 '10 #14

P: 26
Well, I tried changing my code but still no luck!

main.js changed:
Expand|Select|Wrap|Line Numbers
  1. function getObject(f)
  2. {
  3.     var http;
  4.     var url = "send.php";
  5.     var email = f.elements['recipient'];
  6.     var subject = f.elements['title'];
  7.     var body = f.elements['body'];
  8.     var parameters = "e=" + email + "&s=" + subject + "&b=" + body;
  9.  
and
Expand|Select|Wrap|Line Numbers
  1. http.open("GET", url+"?"+parameters, true);
in send.php
Expand|Select|Wrap|Line Numbers
  1. $to = $_GET['e'];
  2. $subject = $_GET['s'];
  3. $message = $_GET['b'];

and in index.html
Expand|Select|Wrap|Line Numbers
  1. <form name="sendmail" action="" method="" class="sender">
Expand|Select|Wrap|Line Numbers
  1. <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?recipient=s&title=d&body=d&submit=Send!

Ok, I'm gonna shoot myself...
Dec 13 '10 #15

Dormilich
Expert Mod 5K+
P: 8,639
index.html?recipient=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.
Dec 13 '10 #16

P: 26
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?
Dec 13 '10 #17

Dormilich
Expert Mod 5K+
P: 8,639
Perhaps this causes the problem?
let me answer very short—yes.
Dec 13 '10 #18

P: 26
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
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2.  
  3. <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5.  
  6. <title> Unimail </title>
  7.  
  8. <script type="text/javascript" src="main.js"></script>
  9. <link rel="shortcut icon" href="/images/favicon.ico" />
  10. <link rel="stylesheet" type="text/css" href="/styles/main.css" />
  11.  
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  13. <meta property="og:description" content="Free one-time use email" />
  14. <meta property="og:title" content="Unimail email service" />
  15. <meta name="author" content="Unimail" />
  16. <meta property="og:site_name" content="Unimail" />
  17.  
  18. </head>
  19.  
  20. <body>
  21.  
  22. <div id="wrapper">
  23. <div id="top">
  24.     <div class="header">
  25.         <img src="/images/email_logo4.jpg" alt="Unimail" />
  26.     </div>
  27.     <div class="navig">
  28.         <ul class="navbar">
  29.             <li><a href="http://localhost/index.html"><span>Home</span></a></li>
  30.             <li><a href="http://localhost/about.html">About us</a></li>
  31.             <li><a href="#">FAQ</a></li>
  32.             <li><a href="#">Contact</a></li>
  33.             <li><a href="#">Other services</a></li>
  34.         </ul>
  35.     </div>
  36. </div>
  37.  
  38. <div id="body">
  39.     <br />
  40.     <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>
  41.  
  42.     <br /><br />
  43.  
  44.     <form name="sendmail" action="" method="" class="sender">
  45.  
  46.         <p>Recipient's address </p> <input name="recipient" type="text" id="recipient" /><br />
  47.         <p> Title </p><input name="title" type="text" id="title" />
  48.         <p> Body </p><textarea rows="15" cols="65" name="body" id="body" ></textarea><br />
  49.         <input name="submit" type="button" value="Send!" onclick="getObject(this.form);"/>
  50.         <span id="error"> </span>
  51.  
  52.     </form>
  53.     <p> Remember! You will not be able to receive any reply! </p>
  54. </div>
  55. <div id="footer">
  56.     <p> This site was created for occasional emailing. Please do not attempt to use this site to spam emails. </p>
  57. </div>
  58.  
  59. </div>
  60.  
  61. </body>
  62.  
  63. </html>
  64.  
Expand|Select|Wrap|Line Numbers
  1. function getObject(f)
  2. {
  3.     var http;
  4.     var url = "send.php";
  5.     var email = f.elements['recipient'].value;
  6.     var subject = f.elements['title'].value;
  7.     var body = f.elements['body'].value;
  8.     var parameters = "e=" + email + "&s=" + subject + "&b=" + body;
  9.  
  10.     try
  11.     {
  12.         http = new XMLHttpRequest();
  13.     }
  14.  
  15.     catch(e)
  16.     {
  17.         try
  18.         {
  19.             http = new ActiveXObject("Msxml2.XMLHTTP");
  20.         }
  21.  
  22.         catch(e)
  23.         {
  24.             http = new ActiveXObject("Microsoft.XMLHTTP");
  25.         }
  26.     }
  27.  
  28.     function getServer()
  29.     {
  30.         if (http.readyState == 4)
  31.         {
  32.             if (http.responseText.match("Error") == "Error")
  33.             {
  34.                 document.getElementById("error").style.color = "red";
  35.                 document.getElementById("error").innerHTML = "  " + http.responseText;
  36.             }
  37.  
  38.             else
  39.             {
  40.                 document.getElementById("error").style.color = "green";
  41.                 document.getElementById("error").innerHTML = "  " + http.responseText;
  42.             }    
  43.         }
  44.     }
  45.  
  46.     http.open("GET", url+"?"+parameters, true);
  47.     http.onreadystatechange = getServer;
  48.     http.send(null);
  49. }
  50.  
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. require_once('class.phpgmailer.php');
  4.  
  5. $emailRep = "";
  6. $titleRep = "";
  7. $bodyRep = "";
  8.  
  9. function verifyEmail($email)
  10. {
  11.     if (filter_var($email, FILTER_VALIDATE_EMAIL) == true)
  12.     {
  13.         return true;
  14.     }
  15.  
  16.     $emailRep = "Error: Invalid email address!";
  17. }
  18.  
  19. function verifyTitle($title)
  20. {
  21.     if (strlen($title) > 0)
  22.     {
  23.         return true;
  24.     }
  25.  
  26.     $titleRep = "Error: Empty titles are not allowed!";
  27. }
  28.  
  29. function verifyBody($body)
  30. {
  31.     if (strlen($body) > 19)
  32.     {
  33.         return true;
  34.     }
  35.  
  36.     $bodyRep = "Error: Your email must consist of at least 20 character!";
  37. }
  38.  
  39. $to = $_GET['e'];
  40. $subject = $_GET['s'];
  41. $message = $_GET['b'];
  42.  
  43. if (verifyEmail($to) && verifyTitle($subject) && verifyBody($message))
  44. {
  45.     $mail = new PHPGMailer();
  46.     $mail->Username = 'unimail.auto@gmail.com';
  47.     $mail->Password = '*******************';
  48.     $mail->From = 'unimail.auto@gmail.com';
  49.     $mail->FromName = 'Unimail';
  50.     $mail->Subject = $subject;
  51.     $mail->AddAddress($to);
  52.     $mail->Body = $message;
  53.     $mail->Send();
  54.  
  55.     echo "Message sent!";
  56. }
  57.  
  58. else
  59. {
  60.     echo $emailRep . "<br />" . $titleRep . "<br />" . $bodyRep;
  61. }
  62.  
  63. ?>
  64.  
Dec 14 '10 #19

Dormilich
Expert Mod 5K+
P: 8,639
on line #45 (JavaScript) insert: alert(parameters);, what does this give?
Dec 14 '10 #20

P: 26
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
Dec 14 '10 #21

Dormilich
Expert Mod 5K+
P: 8,639
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.
Expand|Select|Wrap|Line Numbers
  1. function verifyTitle($text)
  2. {
  3.     # abort if the text length is zero
  4.     if (strlen(trim($text)) == 0)
  5.     {
  6.         throw new LengthException("Empty titles are not allowed!");
  7.     }
  8.     # further input validation/sanitising
  9.     return $text;
  10. }
the other check functions must be coded appropriately. (use an UnexpectedValueException() for verifyEmail() and LengthException() for verifyBody()).

putting it together.
Expand|Select|Wrap|Line Numbers
  1. # I left off the function definitions here
  2.  
  3. # start controlling the flow
  4. try
  5. {
  6.     $title = verifyTitle($_GET['s']);
  7.     $body  = verifyBody($_GET['b']);
  8.     $email = verifyEmail($_GET['e']);
  9.     $mail  = new PHPGMailer();
  10.     // etc.
  11. }
  12. # collect any errors and output the error message
  13. catch (Exception $e)
  14. {
  15.     echo $e->getMessage();
  16. }
  17. # 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.
Dec 14 '10 #22

P: 26
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
Dec 14 '10 #23

Dormilich
Expert Mod 5K+
P: 8,639
that doesn’t happen. Exceptions are thrown once at a time.

all code until the next catch() block is not executed
Dec 14 '10 #24

P: 26
So what happens if a bad title and body is input? I want to display two error messages. How do I do this?
Dec 14 '10 #25

Dormilich
Expert Mod 5K+
P: 8,639
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.
Dec 14 '10 #26

P: 26
Alright! Thanks!!
Dec 14 '10 #27

Post your reply

Sign in to post your reply or Sign up for a free account.