I have a form that looks like this:
Based on Emmett's answer, my ideal fix for this was just to kill the form's submit with Javascript itself, like this:
$(".vote_form").submit(function() { return false; });
And that totally worked.
For completeness, some of my JS code in the original post need a little love. For example, the way I was adding to the serialize function didn't seem to work. This did:
$form.serialize() + "&submit="+ $(this).attr("value")
Here's my entire jQuery code:
$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
Another solution is to use a hidden field, and have the onclick event update its value. This gives you access from javascript, as well as on the server where the hidden field will get posted.
var form = jQuery('#myform');
var data = form.serialize();
// add the button to the form data
var btn = jQuery('button[name=mybuttonname]').attr('value');
data += '&yourpostname=' + btn;
var ajax = jQuery.ajax({
url: url,
type: 'POST',
data: data,
statusCode: {
404: function () {
alert("page not found");
}
}
});
... rest of your code ...
You can also try out the jquery From Plugin which as all sorts of nice tools for submitting forms via ajax.
http://malsup.com/jquery/form/
Without resorting to the Form plugin (which you should use) you should be handling the submit event instead. The code would stay pretty close to the original:
$("form").submit(function()) {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
// work with the response
});
return false;
});
You can trigger the form submit on the click of the images. This will work with the preventDefault().
var vote;
$(".vote_up, .vote_down").click(function(event) {
vote = $(this).attr("class");
$(".vote_form").trigger("submit");
});
$(".vote_form").submit(function(event) {
$form = $(this);
$.post($form.attr("action"), $form.serialize() + "&submit="+ vote, function(data) {
// do something with response (data)
});
event.preventDefault();
});