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!

ChemProfMatt
  • 139
  • 10

2 Answers2

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 );
               }
           });
      });
Raghav
  • 1,014
  • 2
  • 16
  • 34
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.

Community
  • 1
  • 1
Mike G
  • 4,713
  • 2
  • 28
  • 31