Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit a form as JSON (no AJAX)

Is it possible to submit form data as JSON, without using AJAX?

I've tried changing the enctype:

<form enctype="application/json"></form>

But that's not a valid value according on w3schools

The reason I would like this behaviour is that the requested URL will return a file, which I obviously can't do anything with if I use AJAX. I would like to send JSON data marked as Content-Type: application/json so that ASP.NET MVC will use its JSON binding.

like image 795
jeef3 Avatar asked Oct 04 '11 04:10

jeef3


2 Answers

Yes, you can serialize form like an object with plugin. I write a sample for you;

//Head

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.serialize-object.js"></script>

You can download plugin from here

//Form

<form id="frm">
<input type="text" name="Model[Firstname]">
<input type="text" name="Model[Lastname]">
<input type="text" name="ModelDetail[PhoneNumber]">
...
<button type="button" onclick="sendForm()">Send</button>
</form>

//JS

function sendForm(){
model_data = $("#frm").serializeObject();
$.ajax({
url: 'YOUR_SERVICE_URL',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(model_data),
dataType: 'json',
success:function(e){
    // I know, you do not want Ajax, if you callback to page, you can refresh page here
   }
});

Good luck!

like image 139
Phd. Burak Öztürk Avatar answered Nov 14 '22 19:11

Phd. Burak Öztürk


Could you use JSON.stringify() to serialize your client side object and then stuff that into a hidden input and submit your form...and then in the controller side pull it back out of the Request.Form and deserialize it into your object?

[Edit] Just saw in the comment section underneath of the original question that this was essentially a duplicate post and that this stackoverflow worked as a solution.

like image 1
afreeland Avatar answered Nov 14 '22 19:11

afreeland