Reputation: 43
I'm working with this exact same MailChimp PHP/AJAX subscribe processing form - clear text value after success? - but I am absolutely stumped on how to actually get the form field to cleat after success.
Apparently to what Felix recommended here - clear text value after success? - the code works only if the span element exists at document load, and you have to call the if-statement after completion if using Ajax.
Could someone please help me? How do you clear the form field after it has been successfully completed by a user?
Here is the code:
<?php
// store-address.php
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('my-api-key');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "my-list";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form code:
<form action="<?=$_SERVER['PHP_SELF']; ?>" id="signup" class="subscribe" method="get">
<fieldset>
<input type="text" id="email" name="email" placeholder="your email address" />
<input type="submit" name="submit" value="Send it" />
</fieldset>
</form>
<p id="response"><? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?></p>
<script type="text/javascript" src="/js/prototype.js"></script>
<script type="text/javascript" src="/js/mailing-list.js"></script>
The mailing-list javascript code:
// Load Events Listeners
Event.observe(window, 'load', init, false);
function init(){
Event.observe('signup','submit',storeAddress);
}
// AJAX call sending sign up info to store-address.php
function storeAddress(event) {
// Update user interface
$('response').innerHTML = 'Getting email address...';
// Prepare query string and send AJAX request
var pars = 'ajax=true&email=' + escape($F('email'));
var myAjax = new Ajax.Updater('response', 'inc/store-address.php', {method: 'get', parameters: pars});
Event.stop(event); // Stop form from submitting when JS is enabled
}
Upvotes: 0
Views: 7657
Reputation: 2625
There are two solutions to this.
The less elegant one would be to create a JS function the resets every form field value manually.
The better way would be to store a hidden reset input in your form with an ID:
<input type="reset" id="blagh" style="display:none"/>
And simply 'click' it using jQuery:
$('#blagh').click();
Upvotes: 1