I am trying to POST data to a REST api without using AJAX. I want to send the data in JSON format. I have the following code but am stuck trying to figure out how to convert the input field and POST it to the server. Here is my code attempt:
<form id = "myform" method = "post">
id: <input type = "text" id = "user_id" name = "user_id">
data: <input type = "text" id = "user_data" name = "user_data">
<input type = "button" id = "submit" value = "submit" onClick='submitform()'>
</form>
<script language ="javascript" type = "text/javascript" >
function submitform()
{
var url = '/users/' + $('#user_id').val();
$('#myform').attr('action', url);
//
// I think I can use JSON.stringify({"userdata":$('#user_data').val()})
// to get the data into JSON format but how do I post it using js?
//
$("#myform").submit();
}
post() sends some data to the server. It does not cause any redirection unless you do it in your server side code which handles the POST request. I can suggest two solutions: To go to comment page, instead of using JQuery post, you can simply use a 'anchor' tag - <a href="comments.
Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.
You can add a hidden input field with the json value, like this -
function submitform() {
var url = '/users/' + $('#user_id').val();
$('#myform').attr('action', url);
var data = JSON.stringify({
"userdata": $('#user_data').val()
})
$('<input type="hidden" name="json"/>').val(data).appendTo('#myform');
$("#myform").submit();
}
You can access your json using json
parameter (name of hidden input)
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