0

I'm trying to build a subscribe form. I can't run php on my site and I don't want the user leave the main site to subscribe the newsletter. I'm using this example as server side. If you try to put in you email you will get redirected and the error message shows up even if the e-mail was added to the mailchimp list.

<div id="email">
<span>Your email..</span>
<form action="http://simondahla.com/jolliassets/notify.php" id="notify" method="POST">
    <input type="text" placeholder="your@email.com" name="email" id="address" data-validate="validate(required, email)"/>
    <span>We'll never spam or give this address away</span>
    <button type="submit">&#187;</button>
</form>
<span id="result"></span>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#notify').submit(function() {
        var action = $(this).attr('action');
        $.ajax({
            url: action,
            type: 'POST',
            data: {
                email: $('#address').attr('value')
            },
            success: function(data){
                $('#result').html(data).css('color', 'green');
            },
            error: function() {
                $('#result').html('Sorry, an error occurred.').css('color', 'red');
            }
        });
    });
});
</script>

live example of the problem

Simon
  • 120
  • 8
  • possible duplicate of [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Quentin Nov 04 '12 at 14:28
  • Where is the code that actually does the adding to mailchimp? – Rick Calder Nov 04 '12 at 14:46

2 Answers2

1

You need to return false from your submit handler. This is to prevent the browser from executing the default action, i.e. to submit the form the normal way.

$('#notify').submit(function() {
   // .. your ajax call
   return false;
});
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • Thanks! So I changed that. So I don't get redirected to the server, but can I pass the server response messages to the client somehow? No it only says, error to everything i try. – Simon Nov 04 '12 at 14:42
1

From your PHP function you're going to return the values you want given the success or failure of the code.

Succeeded:

print json_encode(array("status"=>"success","message"=>'Successfully added'));

Failed:

print json_encode(array("status"=>"error","message"=>'There was an error'));

Then in the HTML you return that message like this:

success: function(data){
            $('#result').html(content.message).css('color', 'green');
        },
        error: function() {
            $('#result').html(content.message).css('color', 'red');
        }
Rick Calder
  • 18,310
  • 3
  • 24
  • 41