简体   繁体   中英

How to post form data as JSON?

I'm trying to build a registration site for a group project we are working on but can't figure out how to send the form data as json. I've tried googling a lot and changing the code but nothing seems to work. The problem I have is that when i press on the submit button I get an error like this from the API:

{"":["The input was not valid."]}

I think the reason is that my form does not send the data as JSON and it's they format they require according to their API documentation. My form code looks like this:

<form id="register_form" action="https://https://url.com/users/register" method="post">
        <input type="text" pattern="[A-Za-z]{1,20}" placeholder="Name" name="name" title="Up to 20 alphabetical characters" required>
        <input type="email" placeholder="Email" name="email" title="Must be a valid email address" required>
        <input type="password" pattern="[a-zA-Z0-9-]+{8,20}" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
        <input type="text" pattern="[a-zA-Z0-9-]+" placeholder="Homeadress" name="homeadress">
        <input type="text" placeholder="Postnumber" name="postnumber">
        <input type="text" placeholder="City" name="city">
        <br>
        <button value="Submit" type="submit">Register</button>
</form>

And the script i've been trying to get to work looks like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>

<script type="text/javascript">
  $('register_form').on('submit', function(event){

    var obj = $('register_form').serializeJSON();

    $.ajax({
        type: 'POST',
        url: 'https://url.com/users/register',
        dataType: 'json',
        data: JSON.stringify(obj),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
    });

   return false;
 });
</script>

Any help would be greatly appreciated since I'm not very familiar with coding stuff like this.

Edit:

I also tried it with a script like this but still getting the same response:

<script>

$(document).ready(function(){

    $("#submit").on('click', function(){

   var formData = {

        "name": $('input[name=name]').val(),
        "email": $('input[name=email]').val(),
        "password": $('input[name=password]').val(),
        "homeadress": $('input[name=homeadress]').val(),
        "postnumber": $('input[name=postnumber]').val(),
        "city": $('input[name=city]').val()
    };

       $.ajax({
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        url: 'https://url.com/users/register', 
        type : "POST", 
        dataType : 'json', 
        data : JSON.stringify(formData), 
        success : function(result) {

            console.log(result);
        },
        error: function(xhr, resp, text) {
            console.log(xhr, resp, text);
        }
    })
});
});

I tested it with our teachers test api also and the response is this:

{"message":"Bad Request","reason":"val: nil fails spec: :user-system.spec/login-request predicate: map?\\n"}

There's a couple problems here.

  1. Invalid start tag for script element. This was probably a copy and paste error, but worth mentioning:

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script> missing greater than symbol ^ 
  2. Selecting register_form instead of #register_form in two places, the second was unnecessary regardless because you could reference this instead. This also resulted in the form submission not being cancelled.

  3. You didn't include a $.serializeJSON plugin, again I'm assuming this is a copy and paste error.

  4. $.serializeJSON (whichever you choose) should return a JSON string, but you run JSON.stringify on the result, which will be a string inside a string.

  5. https://https:// This isn't a huge issue because it is in the action attribute of a form that should never submit, but worth mentioning.

In the example below I've provided a simple replacement for $.serializeJSON , and corrected the rest of the issues listed above. serialize_form in the code below can be replaced with whatever $.serializeJSON plugin you choose to use.

I have commented out the ajax request as what is really of concern here is getting the JSON from the form data, so I just log it to the console instead so that you can see it is a JSON string. I also removed the pattern attributes and required flags from the input for ease of testing.

 const serialize_form = form => JSON.stringify( Array.from(new FormData(form).entries()) .reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {}) ); $('#register_form').on('submit', function(event) { event.preventDefault(); const json = serialize_form(this); console.log(json); /*$.ajax({ type: 'POST', url: 'https://url.com/users/register', dataType: 'json', data: json, contentType: 'application/json', success: function(data) { alert(data) } });*/ }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="register_form" action="https://url.com/users/register" method="post"> <input type="text" placeholder="Name" name="name" title="Up to 20 alphabetical characters"> <input type="email" placeholder="Email" name="email" title="Must be a valid email address"> <input type="password" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter"> <input type="text" placeholder="Homeadress" name="homeadress"> <input type="text" placeholder="Postnumber" name="postnumber"> <input type="text" placeholder="City" name="city"> <br> <button value="Submit" type="submit">Register</button> </form> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>

<script type="text/javascript">
  $('#registerForm').on('submit', function(event){

    var obj = $('#registerForm').serializeJSON();

    $.ajax({
        type: 'POST',
        url: 'https://url.com/users/register',
        dataType: 'json',
        data: JSON.stringify(obj),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
    });

   return false;
 });
</script>

try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM