Submitting a jQuery ajax form with two submit buttons

I have a form that looks like this:

<form action="/vote/" method="post" class="vote_form"> <input type="hidden" name="question_id" value="10" /> <input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" /> <input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" /> </form>

When I bind to the form's submit ($("vote_form").submit()), I don't seem to have access to which image the user clicked on. So I'm trying to bind to clicking on the image itself ($(".vote_down, .vote_up").click()), which always submits the form, regardless of whether I try

  • return false;
  • event.stopPropogation(); or
  • event.preventDefault();

because all of those are form events.

  1. Should I attach my $.post() to the form.submit() event, and if so, how do I tell which input the user clicked on, or
  2. Should I attach my $.post() to the image click, and if so, how do I prevent the form from submitting also.

Here is what my jQuery code looks like now:

$(".vote_up, .vote_down").click(function (event) { $form = $(this).parent("form"); $.post($form.attr("action"), $form.find("input").serialize() + { 'submit': $(this).attr("value") }, function (data) { // do something with data }); return false; // <--- This doesn't prevent form from submitting; what does!? });

-------------Problems Reply------------

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.

I don't get how return false and preventDefault failed to do their job. Maybe try replacing the image buttons with linked images:

<a href="#" class="vote_down"><img src="vote_down.png"/></a>

$('#vote_form > a').click(function(e) {
e.preventDefault();

//one way to know which image was clicked
alert($(this).attr('class'));

$.post(...
});

You can always ensure that a form does not submit by binding to the submit event, e.g.:

$('#vote_form').submit(function() {
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();
});

Try adding onsubmit="return false;" to your form, and then submitting your form with javascript:

<form action="/vote/" method="post" name="vote_form" class="vote_form" onsubmit="return false;">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" onclick="imageClicked(this)"/>
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" onclick="imageClicked(this)"/>
</form>

<script>
function imageClicked(img) {
alert(img.className);
document.forms["vote_form"].submit();
}
</script>

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;
});

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 ...

Category:jquery Views:1 Time:2009-09-01

Related post

  • How to implement validation with jQuery on a asp.Net submit button? 2011-04-05

    I want to call some web-service webmethods on asp.net submit button's click in order to validate the form regarding to some business logic and then I would like to have the button to go on its default behavior if the validation is OK. How can I stop

  • jQuery validation and ajaxForm needs submit button to be clicked twice 2012-04-16

    I have the following jquery function in my code. I have to click the 'submit' button twice to get the form submit to work. I could use ajaxSubmit function and then everything works fine but the problem with jquery is that the submit button's value it

  • jQuery submit ajax form with 2 submit buttons 2010-07-18

    im trying to achieve the following, in php i have a form like this: <form method="post" id="form_1" action="php.php"> <input type="submit" value="add" name="sub"/> <input type="submit" value="envoi" name="sub"/> </form> the fo

  • How to stop form from submitting using Jquery/Ajax 2011-07-11

    This is the code I have. I want to prevent the form from submitting if the message i receive from the php side is 0 (an error occured). If the message received is 1 I want to submit the form. $(document).ready(function(){ $('#form').submit(function(e

  • How to show jquery message after clicking on submit button 2010-07-31

    I am new to jquery and would like to learn how to show a message (e.x please wait in green color or submitting ) after clicking on the submit button. Can you please help --------------Solutions------------- May be this will help: $('#submitButtonID')

  • How do I use jQuery to disable a textarea + Submit button? 2010-12-16

    After a user submits a comment, I want the textarea and summit button to be "disabled" and somewhat visually disabled. Like Youtube. How can I do that with Jquery using the simplest plugin and/or method? --------------Solutions------------- Simply se

  • jQuery validate does not return submit button name 2011-09-02

    I need help here. My jQuery code does not return the submit button name in the $_POST Array... This is my code: <script type="text/javascript"> $(document).ready(function(){ $('#submForm').validate({ submitHandler: function(form) { // Do cleanu

  • ASP.Net C# Ajax Form Validation and Submit button status 2012-04-13

    I have a quite complicated form, and i would like to validate the form before it is submitted in some nice looking ajax way. As part of this i would also like to only enable the forms submit button once the form is correctly filled in. I'm using C#/a

  • AJAX behaving differently for Submit button vs. this.form.submit? 2009-07-16

    I'm trying to auto-save a selection in a dropdown (ASP.NET, MVC, VB), but it's not behaving as expected. Here's the dummy action in the controller: <AcceptVerbs(HttpVerbs.Post)> _ Function TestAction(ByVal id As Integer) As ActionResult Return

  • jquery show processing image on submit button click but hide if css error class exists in the form 2011-04-01

    I have the following jQuery code: $("#signUpFormSubmitButton").click(function(){ $('#processing').show(); }); This works fine. When the submit button is clicked on the form, I show a processing spinning graphic. I don't want to show the processing sp

  • Is there a more concise jQuery syntax to disable a submit button on form submit? 2011-10-01

    I have the following code to disable a submit button when the form is submitted: $('#myform').submit(function(){ $('input[type=submit]', this).attr('disabled', 'disabled'); }); Is there a more concise syntax for this? --------------Solutions---------

  • Firing Ajax call when click submit button 2012-03-13

    In my Rails 3.1 application I have a Jquery dialog that pops up when clicked, and inside that you have a submit button. I have made somewhat an attempt at making this 'submit' button ajax. So that when it is clicked it updates the appointment time an

  • ajax background process after submit button 2012-04-15

    the script I post works fine, it just execute in background my php code at the load of the page.. What I cannot do is to start the php in background after having pressed a submit button.. I tried to add a form in the body but I don't know how to link

  • Jquery Form Field Focus Change Submit Button Class 2010-11-11

    I have the following form: <input name="q" value="" class="qa-search-field"> <input type="submit" value="Search" class="qa-search-button"> I am trying to get the submit button's class to change when the qa-search-field is active by adding

  • jquery.ajax not working for asp:button 2011-08-21

    I am using the following code to get time from the server. The btnNoP .click function returns the proper time, however the asp:Button returns alert Error on page. How can i successfully call a webmethod from document.ready when a asp:button is clicke

  • jQuery form accept checkbox, disable submit button 2011-09-20

    I have a form which enables the submit button only when a checkbox is selected. The problem is that people without JavaScript will never be able to enable the submit button. What is the best solution to this problem? <script src="http://www.lentic

  • Submitting two different forms from a single submit button in PHP? 2011-12-17

    How to submit two different forms dat,a each having a submit button, in two different tables in the same database after clicking on the second form's submit button using PHP? --------------Solutions------------- Create the a number of hidden fields i

  • jQuery - How to dynamically hide submit button when you delete e-mail at input field? 2012-02-08

    Notice it when you type a valid e-mail... then delete this email and it doesn't hide submit button. There a jsFiddle: http://jsfiddle.net/BGNsS/ Can anyone help me? thx! --------------Solutions------------- Check for a valid regex and the length. You

  • How to close a jquery dialog box when a submit button is clicked(Submit button is residing inside the dialog box) 2012-03-28

    i have struts2 form inside a jquery dialog box, when i submit my form inside that dialog box my Struts2 action is performing but that pop up jquery dialog box is not closing. How can i close that dialog box when![enter image description here][1] i su

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.100 (s). 11 q(s)