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: -
<!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: -
<?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: -
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
26 2660 Dormilich 8,658
Recognized Expert Moderator Expert
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;
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
Dormilich 8,658
Recognized Expert Moderator Expert
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)
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.
Dormilich 8,658
Recognized Expert Moderator Expert
Why does it stay on the same page for them, and not for me?
because they don’t use a submit button.
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).
Dormilich 8,658
Recognized Expert Moderator Expert
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?
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.
Dormilich 8,658
Recognized Expert Moderator Expert
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.
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 =/
Dormilich 8,658
Recognized Expert Moderator Expert
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)
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: - $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...=/
Dormilich 8,658
Recognized Expert Moderator Expert
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.
Well, I tried changing my code but still no luck!
main.js changed: - 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 - http.open("GET", url+"?"+parameters, true);
in send.php - $to = $_GET['e'];
-
$subject = $_GET['s'];
-
$message = $_GET['b'];
and in index.html - <form name="sendmail" action="" method="" class="sender">
-
<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...
Dormilich 8,658
Recognized Expert Moderator Expert
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.
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?
Dormilich 8,658
Recognized Expert Moderator Expert
Perhaps this causes the problem?
let me answer very short—yes.
Dormilich 8,658
Recognized Expert Moderator Expert
on line #45 (JavaScript) insert: alert(parameters); , what does this give?
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
Dormilich 8,658
Recognized Expert Moderator Expert
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. - 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 UnexpectedValueException() for verifyEmail() and LengthException() for verifyBody()).
putting it together. - # 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.
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
Dormilich 8,658
Recognized Expert Moderator Expert
that doesn’t happen. Exceptions are thrown once at a time.
all code until the next catch() block is not executed
So what happens if a bad title and body is input? I want to display two error messages. How do I do this?
Dormilich 8,658
Recognized Expert Moderator Expert
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: k.mitz |
last post by:
Hi,
I have a PHP application that allows users to generate a .pdf report of
their database content. Normally, I've had to refresh a page to call
the script to generate the report, so there's a...
|
by: joeakabloo |
last post by:
I've been working on an AJAX web app, my first one actually.
Run into an issue I'm not sure how to resolve (been googling and
reading trying to find a fix).
Basic premise: Using AJAX to handle...
|
by: yonido |
last post by:
hey
my final goal: to add a link to an email message, that will contact my
server & mark the email as "important", with no popup windows/annoying
messages.
id like to do this in ajax, but the...
|
by: BeeRich |
last post by:
Hi folks.
I built an ajax.updater reply in a website on a Mac, and she works
fine. It's a simple reply, the html supplied is correct, and I also
supply the target DIV as well.
Just wondering...
|
by: Samuel |
last post by:
Hi,
I have ASP.NET user control that implements ICallbackEventHandler. Partial
postback works perfectly when I put control on a regular webform.
But when I put it on page that has master page...
| |
by: sebastian.janoschka |
last post by:
Hi,
I build my first Drag & Drop with JavaScript and I would like to drag
the pictures when I click on it.
When I create a normal div tag with some text the script works, but
when I put a...
|
by: gunimpi |
last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431
********************************************************
VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help
wanted...
|
by: Tony Sedgwick |
last post by:
I have installed the AJAX extensions and partial page rendering works ok
from a new ajax enabled web site I created in VS. The problem is that I've
manually entered the necessary entries into the...
|
by: jrnail23 |
last post by:
I have a user control which contains an UpdatePanel, which contains a
MultiView inside, with a GridView in one of the views.
In my GridView, I have a ButtonField which is supposed to trigger a...
|
by: krg |
last post by:
Hi,
I started writing this blog some time back and it would be
great if I could get an audience here and even better if we could have
a conversation about developments possible on the techniques I...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |