Add JSON data to POST request

I have an AJAX form that submits correctly and sends the full model to the controller. I want to add JSON to send with the request. I managed to intercept POST as follows:

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

What I don't know is how to send JSON data, and also save the originally submitted data in a form. I thought about adding a hidden field by setting its value to a JSON string and then de-serializing it on the server, but this seems wrong.

+6
source share
4 answers

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

+3
source

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

Using:

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

+2
source

If you read the information from the jQuery documentation, you may notice that $. post () has a data parameter.

  • data : a card or line sent to the server with the request.

Example:

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

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

0
source

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

For data, you can use $("form").serialize() to get all the form data. Then you can add additional data manually, like this var data = $("form").serialize() + ",other=data" . This can become messy if you want to add a lot of data. A simpler option would be to add hidden fields inside the form, and they will be included in the data when serialize() called

Example: -This will place all the data, including hidden fields containing additional data.

 $.post('www.magicurl.com/api', $("form").serialize(), function (data) { //process data from server }); 
0
source

Source: https://habr.com/ru/post/923386/


All Articles