7

I have an AJAX form that submits correctly and that sends a complete model into the controller. What I want is to add a JSON to be sent with the Request. I have managed to intercept the POST like this:

$(document).ready(function() {
    $("form").submit(function(e) {
        if (e.originalEvent.explicitOriginalTarget.id == "submit") {
        }
    });

What I don't know is how to send my JSON data, while also keeping the data sent initially on the form submission. I had a thought at adding a hidden field, setting its value to the JSON string and then de-serializing it on the server, but that seems rather wrong.

Adrian Marinica
  • 2,191
  • 5
  • 29
  • 53

4 Answers4

5

If you cannot use AJAX, you will have to use a hidden field to store the JSON data inside the form. Otherwise your JSON will never be sent to the server. The HTML specification clearly states the rules: only the values contained in input fields inside the form are sent to the server when this form is submitted.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I struggled for hours trying to avoid doing what you suggested, but it seems that it is the only way that actually works. After sending the JSON as a string to Controller, I deserialized it and got what I needed. If anybody else finds a better way, I am open for changes. Thanks again. – Adrian Marinica Aug 21 '12 at 14:18
2

Feel free to use jQuery my function:

$.fn.addHiddenInputData = function(data) {          
      var keys = {};          
      var addData = function(data, prefix) {          
          for(var key in data) {
              var value = data[key];
              if(!prefix) {
                var nprefix = key;                                            
              }else{
                var nprefix = prefix + '['+key+']';
              }
              if(typeof(value) == 'object') {                                    
                  addData(value, nprefix);
                  continue;
              }
              keys[nprefix] = value;
          }          
      }          
      addData(data);          
      var $form = $(this);      
      for(var k in keys) {
          $form.addHiddenInput(k, keys[k]);
      }

}
$.fn.addHiddenInput = function(key, value) {      
      var $input = $('<input type="hidden" name="'+key+'" />')
      $input.val(value);
      $(this).append($input);

}

Usage:

// click event is fired before submit event
$('#form input[type="submit"]').click(function(){

  // add some JSON data before submit
  $('#form').addHiddenInputData({
    'foo': 123,
    'bar': 456,
    'foo2': {
      'bar': 123
    }
  });
});

No need to use ajax.

Peter
  • 16,453
  • 8
  • 51
  • 77
  • How would I send an array of objects using your method? Simply putting the array in addHiddenInputData as a parameter doesn't seem to work, as I receive the array null on the controller. – Adrian Marinica Aug 21 '12 at 13:38
  • do it like this: `{array: [1,2,3,4,5]}` – Peter Aug 21 '12 at 13:39
  • With int's / strings it works, but not with bigger objects. :( – Adrian Marinica Aug 21 '12 at 13:43
  • I ended up using a hidden field, although I hate this solution. I believe the problem is the content type of my request, since the array count is correct, only the values are the default ones (0, null etc). I have upvoted you, though. Thanks! :) – Adrian Marinica Aug 21 '12 at 14:19
0

If you read the info from jQuery documentation you can notice that $.post() has a Data option.

  • data : A map or string that is sent to the server with the request.

Example :

$.post("test.php", { name: "AdrianMar" } );

You can get your form values with a usual $("form").serialize().

Gil Zumbrunnen
  • 1,062
  • 6
  • 17
0

To do the actual Ajax post, you can use JQuery.Ajax (has more options), or JQuery.Post

For the data, you can use $("form").serialize() to get all the form's data. You can then add the additional data manually like this var data = $("form").serialize() + ",other=data". This can get messy if you want to add lots of data. The easier option would be to add hidden fields inside the form and they will be included in the data when you call serialize()

Sample: -this will post all data including the hidden fields that contain the extra data.

$.post('www.magicurl.com/api', $("form").serialize(),
                function (data) {
                    //process data from server
                });
robasta
  • 4,621
  • 5
  • 35
  • 53