18

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

2
  • 1
    insert json into a hidden input. Commented Jun 14, 2013 at 20:12
  • Also, you can get rid of the onclick event and just use a submit event if you want, $("#myform").submit(function(){ $("#jsonvalue").val(JSON.stringify({"userdata":$('#user_data').val()}));}); by not returning false, it will continue to submit with the updated hidden input value. Commented Jun 14, 2013 at 20:14

1 Answer 1

23

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)

Sign up to request clarification or add additional context in comments.

1 Comment

This is all great and all, but how to than parse the json from the PHP server-side, I've tried using json_decode($_POST['json']) but it returns NULL value here. I can not change entire form to JSON as there are other fields in the form that need to be passed via the regular form post way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.