Reputation: 11131
I have a working request I've created in Postman. In this request, I'm POSTing data to an endpoint at http://localhost:21124/submissions/[someId]
. In Postman, I have a Header key called Content-Type
with a value of application/x-www-form-urlencoded
.
In the Body tab in Postman, I have the x-www-form-urlencoded radio button selected. I then have a number of key-value pairs entered. When I POST this request, it works successfully. I'm now trying to rebuild this request as an HTML form.
In an attempt to rebuild the request as an HTML form, I have:
function submitClick() {
var form = $('#myForm');
$.ajax({
url: '/submissions/2e5f7619-23a5-425c-a39c-97928e3c2f9a',
data: form.serialize(),
type: 'POST'
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" method="post">
<label for="emailAddress">Email address</label>
<input type="email" id="emailAddress">
<label for="name">Name</label>
<input type="text" id="name">
<button onclick="return submitClick();">Submit</button>
</form>
When I click the "submit" button, I'm not seeing my values in my controller. I can successfully see them when I post via Postman. This would mean that the values are getting POSTed two different ways. However, I'm not sure why. Can someone please explain the difference to me?
Thanks
Upvotes: 0
Views: 213
Reputation: 61784
Your form elements don't have any "name" attributes. This is required in order for the element to be serialised by jQuery and sent in the request data.
Also, you could make the script a bit neater by using jQuery's syntax to handle the form's submit
event directly:
Script
$('#myForm').submit(function(event) {
event.preventDefault(); //prevent a (default) full postback
$.ajax({
url: '/submissions/2e5f7619-23a5-425c-a39c-97928e3c2f9a',
data: $(this).serialize(),
type: 'POST'
});
});
HTML
You haven't shown the controller code, so for the sake of example I'm going to assume the names of the fields the server is expecting to receive match the ID attributes of the form elements. However you'll need to ensure they match what the controller expects in order for the controller to recognise them.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" method="post">
<label for="emailAddress">Email address</label>
<input type="email" id="emailAddress" name="emailAddress">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<button type="submit" id="submitMyForm" name="submitMyForm" >Submit</button>
</form>
Upvotes: 1