Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST JSON Data from form without AJAX

Tags:

json

jquery

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();
}

like image 524
user1884367 Avatar asked Jun 14 '13 20:06

user1884367


People also ask

How to post data in JQuery without AJAX?

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.

How to pass JSON object in formData?

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.


1 Answers

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)

like image 156
Mohammad Adil Avatar answered Sep 18 '22 13:09

Mohammad Adil