Reputation: 14254
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;
});
Upvotes: 2
Views: 3318
Reputation: 2585
Why not just use click handler instead and create your own object, as you have only two fields you want to send, it shouldnt be a problem;
var data = {
'email': $('input[name="email"]').val(),
'submit': $(this).val()
}
data.serialize();
Upvotes: 2
Reputation: 943579
Use click handlers on the buttons instead of a submit handler on the form. Add this.value
to the data you send to the server.
Upvotes: 2