This is on a WordPress site. I am using the following php to take a user’s email from an input box and add it to my mailchimp list. There is a js and php page that does all the heavy mailchimp stuff, but that shouldn’t be important for my question:
<?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(); }
?>
Then on the page where the user enters the email, it grabs the response and displays the message result. Here is that part:
<div id="emailList">
<form id="signup" action="<?=$_SERVER['PHP_SELF']; ?>" method="get" >
<label>signup for our email list</label>
<input type="text" id="email" class="email" name="email" />
<input type="submit" value="OK" id="emailSubmit" name="submit" />
</form>
<script type="text/javascript" src="path/to/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="path/to/js/mailing-list.js"></script>
</div><!-- end emailList -->
<div id="response">
<? require_once('inc/store-address.php');
if($_GET['submit'])
{
echo storeAddress();
} ?>
</div><!-- end response-->
<script type="text/javascript">
$(document).ready(function() {
$("#emailSubmit").click(function() {
$('#response').fadeIn(1500).delay(3500).fadeOut(1500);
});
});
</script>
My question is simple. How can I implement something so that if it was successful and it returns the message “Success! Check your email to confirm sign up.” it will just clear the value of the input box instead of leaving it prefilled? the input box id is “email”.
I think I need to use .val("") somehow, but I don’t see how I can have it clear the email only if it was successful.
One simple solution is:
PHP
JS
edit: full ajax solution