skip to Main Content

I have a web page built with Bootstrap and jQuery.

A modal dialog box displays a simple form. On button click, it posts the form contents as JSON to my REST web service.

Here’s the modal dialog …

<!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Create New User</h4>
        </div>
        <div class="modal-body">

          <form id="createForm">
              <p><input id="firstName" type="text"/>
              <p><input id="lastName" type="text"/>
              <p><input id="emailAddr" type="text"/>
              <button id = "doCreateButton" class="btn btn-primary" type="submit">Submit</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </form>

        </div>
    </div>
  </div>

Here’s the script that does the POST …

<script>
    $(function() {
        //twitter bootstrap script
        $("#doCreateButton").click(function() {
            $.ajax({
                type : "POST",
                url : "http://localhost:8080/myapp/json/user/create",
                data : JSON.stringify( $('#createForm').serialize()),
                success : function(msg) {
                    $("myModal").modal('hide');
                },
                error : function() {
                    alert("failure");
                },
                done : function(e) {
                    console.log("DONE");
                    $("myModal").modal('hide');
                }
            });
        });
    });
</script>

The problem, is the text that gets sent to the REST web service is this …

%22%22=

What am I doing wrong?

UPDATE:

Here’s a snippet of from the backend, a REST service built with Spring Web @RestController …

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/.../

@RestController
public class WebRestController {

    @Autowired
    UserService userService;

    public WebRestController() {
        // TODO Auto-generated constructor stub
    }

    @RequestMapping(value = "/json/user/create", method = RequestMethod.POST)
    public ResponseEntity<String> createUser(@RequestBody String json) throws Exception {

        /* ... do stuff ... */

        return new ResponseEntity<String>(replyObj.toJSONString(), HttpStatus.OK);  
    }   

3

Answers


  1.          var formData= $('#createForm').serialize()  ;   
             $.ajax({
                        type : "POST",
                        url : "http://localhost:8080/myapp/json/user/create",
                        data :  {formData:formData},
                        dataType: 'json',
                        success : function(msg) {
                            $("myModal").modal('hide');
                        },
                        error : function() {
                            alert("failure");
                        },
                        done : function(e) {
                            console.log("DONE");
                            $("myModal").modal('hide');
                        }
                  });
    

    You can try this.

    Login or Signup to reply.
  2. Firstly, JSON.stringify( $('#createForm').serialize()); returns

    ""firstName=Robert&lastName=Hume&emailAddr=RobertHume%40gmail.com""
    

    You can send data JSON like this:

    var frm = $("#createForm").serializeArray();
          var obj = {};
          for (var a = 0; a < frm.length; a++) {
             obj[frm[a].name] = frm[a].value;
          }
            var jsonData = JSON.stringify(obj);
    

    jsonData variable is now json

    "{"firstName":"Robert","lastName":"Hume","emailAddr":"[email protected]"}"
    

    Here is the Ajax Request.

    <script>
        $(function() {
            //twitter bootstrap script
            $("#doCreateButton").click(function() {
                $.ajax({
                    type : "POST",
                    url : "http://localhost:8080/myapp/json/user/create",
                    data : jsonData, //sending here..
                    success : function(msg) {
                        $("myModal").modal('hide');
                    },
                    error : function() {
                        alert("failure");
                    },
                    done : function(e) {
                        console.log("DONE");
                        $("myModal").modal('hide');
                    }
                });
            });
        });
    </script>
    

    Finally, on the Server side, you should catch the @RequestBody UserRequest userRequest by creating request dto class like below.

    public class UserRequest{
        String    firstName;
        String    lastName;
        String    emailAddr;
    
          //getter
          //setter
    
    }
    
    Login or Signup to reply.
  3. Thanks for the help everyone. In the end, I got it working like this:

    $(function() {
        //twitter bootstrap script
        $("#doCreateButton").click(function() {
    
            var formData = {
                      firstName:$('#firstName').val(),
                      lastName:$('#lastName').val(),
                      emailAddr:$('#emailAddr').val()
            };
            var sJSON = JSON.stringify(formData);
            alert( sJSON );
            $.ajax({
                type : "POST",
                url : "http://localhost:8080/myapp/json/user/create",
                data : sJSON,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success : function(msg) {
                    $("#thanks").html(msg)
                },
                error : function() {
                    alert("failure");
                },
                done : function(e) {
                    console.log("DONE");
                    $("myModal").modal('hide');
                }
            });
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search