I am trying to hardwire an on-the-fly created form to send JSON using the encoding type "application/json
".
in jQuery, I would set this as 'contentType
' in an $.ajax
or a $.post
- however for certain reasons, I need to be doing this manually.
I have the following code, but it just doesn't work. It still defaults the enctype to application/x-www-form-urlencoded
data = data;
var form = document.createElement("FORM");
form.style.display = "none";
form.action = url;
form.setAttribute('enctype', 'application/json');
form.method = "post";
Am I trying to set the wrong property, or am I just setting it wrong? Any ideas?
I am trying to hardwire an on-the-fly created form to send JSON using the encoding type "application/json
".
in jQuery, I would set this as 'contentType
' in an $.ajax
or a $.post
- however for certain reasons, I need to be doing this manually.
I have the following code, but it just doesn't work. It still defaults the enctype to application/x-www-form-urlencoded
data = data;
var form = document.createElement("FORM");
form.style.display = "none";
form.action = url;
form.setAttribute('enctype', 'application/json');
form.method = "post";
Am I trying to set the wrong property, or am I just setting it wrong? Any ideas?
Share Improve this question asked Nov 10, 2010 at 23:50 CielCiel 17.8k25 gold badges107 silver badges202 bronze badges 1- darobin.github.io/formic/specs/json - it is an unofficial W3C draft as of 03 March 2014. I haven't seen it actually implemented yet. – chowey Commented May 13, 2014 at 1:07
4 Answers
Reset to default 4Not sure that 'application/json' is supported as a valid enctype. According to the HTML401 specification:
"W3C User agents must support the content types listed below (application/x-www-form-urlencoded, multipart/form-data). Behavior for other content types is unspecified."
http://www.w3/TR/html401/interact/forms.html#form-content-type
So I guess that support for this is down to the browser vendor.
If you want to mimic the way jQuery and other javascript libraries work then you'll be using an xmlhttp request to post your data instead of using a FORM element, you dont need to tell the server what kind of content type you'll be sending when you do this, the server will assume (rightfully) that you are using application/x-www-form-urlencoded .
I don't think a form
can do that.
You'll need to do it on the server side. Or if you must do it on client prior to sending (not remended) then look at a JSON library.
You should check out the w3Schools reference.
form.enctype = enctype;
EDIT - I didn't notice you wanted the form to encode the data into JSON...that's not going to happen. Either use AJAX or process it server side and return the response in JSON.
I believe that you should use
enctype="multipart/form-data"