Reputation: 1
I'm fairly new when it comes to using scripting languages so I'm struggling to get my head round the concepts.
Basically I have this form
<form method="post" action="/list/process.php">
<input type="email" name="address" value ="Email" />
<input type="hidden" name="lists[]" value="122" />
<input type="submit" name="submit" value="Join" />
</form>
process.php validates the email address for the correct syntax and if successful checks the address against a database to see if it already exists ("unsubscribe") or not ("subscribe")
I included this snippet of PHP to the page of the form
<div id="result">
<?php
if ($_SESSION['result'] == ("fail"))
{
echo "<p>Please enter a valid email address!</p>";
}
if ($_SESSION['result'] == ("success") && $_SESSION['action'] == ("subscribe"))
{
echo "<p>Thankyou for joining, you will shortly receive an email at $_SESSION[address]' with a link to your free download.</p><p>Note: if you do not receive an email, please check your junk folder and mark the message as safe.</p>";
}
if ($_SESSION['result'] == ("success") && $_SESSION['action'] == ("unsubscribe"))
{
echo "<p>You will shortly receive an email with a link to unsubscribe from the mailing list.</p>";
}
?>
</div>
Not sure if my PHP syntax is up to scratch (I'm new to it) but it works. Of course div#result shows up as "Please enter a valid email address!" when you initially load up the page because $_SESSION['result'] comes back with "fail". All of the other possibilities work when I submit the form.
Now how would I go about replicating this PHP snippet in AJAX? I imagine that it would involve posting the form to process.php using AJAX, getting the three session variables back, and then processing them in the above manner (but in JavaScript) to display one of the three messages in an initially hidden div (#result) in a popup/bubble manner.
The question is how? I have no experience in using AJAX and it seems like the only way I can achieve the desired outcome.
Thankyou for your help.
Adam
Upvotes: 0
Views: 160
Reputation: 33441
I think the use of sessions is probably unnecessary in this instance.
Here's what I would do:
div#result
with javascript.process.php
, process the form and return a JSON array containing a list of error messages and a variable denoting whether submission was successful.div#result
and unhide the div.Upvotes: 1