javascript - preventDefault() not stopping regular form submit -
i'm trying code ajax contact form sends email. i'm following tutorial found here.
i'm having trouble preventing browser navigating url indicated on form's action attribute.
here's javascript code:
$(function(){ var form = $('#ajaxmail'); var formsuccess = $('#successmail'); var formerror = $('#errormail'); $(form).submit(function(event){ event.preventdefault(); var formdata = $(form).serialize(); $.ajax({ type: 'post', url: $(form).attr('action'), data: formdata }) .done(function(response){ $(successmail).removeclass('standbymessage'); $(successmail).addclass('completedmessage'); $('#name').val(''); $('#email').val(''); $('#message').val(''); )} .fail(function(response){ $(errormail).removeclass('standbymessage'); $(errormail).addclass('completedmessage'); )}; } });
html code
<form name="ajaxmail" id="ajaxmail" action="mailer.php" method="post"> <input type="text" id="name" name="name" placeholder="<?php echo $plname; ?>" required> <input type="text" id="email" name="email" placeholder="<?php echo $plemail; ?>" required> <textarea id="message" name="message" cols="63" rows="8" placeholder="<?php echo $plmessage; ?>" required></textarea> <input type="submit" id="submitmail" value="<?php echo $plsend; ?>"> </form> <div id="successmail" class="alert alert-success standbymessage" role="alert"><strong>correo electronico</strong> enviado correctamente.</div> <div id="errormail" class="alert alert-danger standbymessage" role="alert"><strong>correo electronico</strong> no pudo enviarse, intente de nuevo mas tarde</div>
you have wrong closing brackets between submit,done , close check that
corrected script:
$(document).ready(function(){ var submitform = $('#ajaxmail'); var formsuccess = $('#successmail'); var formerror = $('#errormail'); $(submitform).on('submit',function(event){ event.preventdefault(); var formdata = $(submitform).serialize(); $.ajax({ type: 'post', url: $(submitform).attr('action'), data: formdata }) .done(function(response){ $(successmail).removeclass('standbymessage'); $(successmail).addclass('completedmessage'); $('#name').val(''); $('#email').val(''); $('#message').val(''); }) .fail(function(response){ $(errormail).removeclass('standbymessage'); $(errormail).addclass('completedmessage'); }); }); });
Comments
Post a Comment