I have a basic newsletter signup form with an email field and two buttons (subscribe and unsubscribe). I want to submit the button value as part of the ajax data but .serialize() does not include button values since they are specific to an event.
Here is my code: Javascript:
$('#newsletter_form').submit(function() {
$.ajax({
type:'POST',
url:'/newsletter',
data: $(this).serialize(),
dataType:'json',
success: function(data) {
if(data['status'] == true) {
alert(data['status']);
}
else {
alert(data['error']);
}
}
});
return false;
});
HTML:
<form id="newsletter_form"action="/newsletter/" method="post">
<input type="text" name="email" value="Email Address" class="toggle"/>
<button class="btn_grey" name="submit" type="submit" value="subscribe"><span>Subscribe</span></button>
<button class="btn_grey" name="submit" type="submit" value="unsubscribe"><span>Unsubscribe</span></button>
</form>
Edit I fixed this by using a click event on the buttons and using parent().serialize() plus attr("value") for the request data.
$('#newsletter_form button').click(function() {
$.ajax({
type:'POST',
url:'/newsletter',
data: $(this).parent('form').serialize() + '&submit='+ $(this).attr("value"),
dataType:'json',
success: function(data) {
if(data['status'] == true) {
alert(data['status']);
}
else {
alert(data['error']);
}
}
});
return false;
});