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.
To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With