0

I have an MVC project I'm working on, and am creating a set of different submit buttons, each which pass a different value to the controller on submission.

In my current code, I have the call to the submit function first create hidden input elements to pass the data I want, something like this:

    $('#btnCreate').live('click', function () {
    $('#formIndex').submit(function (event) {
        $('#actions').append('<input type="hidden" name="objectId" value="' + $('input[name="objectList"]').val() + '" />');
        $('#actions').append('<input type="hidden" name="choice" value="create" />');
    });
});

I'm wondering if I can just pass the values of those hidden inputs as a set of parameters in the submit call, like you can do with the $.get, $.post, and $.ajax functions. I've experimented but haven't seemed to hit on the right formula yet.

Thanks for your help!

2
  • Are you looking for an ajax solution or a synchronous submit? Commented Oct 2, 2011 at 0:53
  • In this case I'm looking for synchronous. I want to submit and then redirect to another page. Commented Oct 2, 2011 at 4:42

2 Answers 2

1

I think you are on the right track by adding hidden input parameters. I don't know of any other way to append data to your non-ajax form submit.

You might want to change a few things about your code though:

  1. Build your hidden inputs using jquery (as seen here on SO)

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla"); $('#form1').append($(input));

  2. For better performance, use delegate() instead of live(). The performance benefit really depends on how deep your DOM is. However, delegate supports chaining where live does not. (In jquery 1.7, all these problems go away with the on() method...):

    $('body').delegate('#btnCreate', 'click', function () { ... });

Note that instead of using body as the container element, you could instead use something lower in the DOM which wraps your btnCreate element.

Sign up to request clarification or add additional context in comments.

Comments

1

If you have to just submit data in the form to the backend, you can use serialize() function of jquery.

Usage:

      $('form').submit(function() {
         var yourdata = $(this).serialize();
        $.ajax({
                type: "POST",
                 url: "check.php",
                data: yourdata,
             success: function(msg){
                      alert( "Data Saved: " + msg );
               }
           });
      });

1 Comment

This is asynchronous, he is looking for synchronous

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.