Review a jQuery Ajax form submit.


    $(document).ready(function () {

        $("#hostingForm").submit(function (e) {

            e.preventDefault(e);

            var data = {}
            data["id"] = $("#id").val();
            data["domain"] = $("#domain").val();
            data["name"] = $("#name").val();
            //...

            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "{{home}}/hosting/update",
                data: JSON.stringify(data),
                dataType: 'json',
                timeout: 600000,
                success: function (data) {
                  
                    console.log("SUCCESS: ", data);
                },
                error: function (e) {
                    
                    console.log("ERROR: ", e);
                }
            });

        });
    });

Review the server side (Spring MVC) to receive the Ajax request.


@RestController
@RequestMapping("/hosting")
public class AdminHostingController {

    @Autowired
    HostingBo hostingBo;

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateHosting(@RequestBody HostingForm hostingForm) {

        if(hostingForm!=null){
            hostingBo.update(hostingForm, UpdatedBy.WEB);
        }

        return "success";

    }

The above Spring MVC code is working fine, updated the database and return a ‘success’ string.

1. Problem

Both client side (jQuery Ajax form submit) and server side (Spring MVC) are working fine, but the Ajax error event is fired?

See the following output in the browser console :

ERROR:  Object {readyState: 4, responseText: "success", status: 200, statusText: "OK"}

200 OK but error event is fired?

2. Solution

In jQuery .ajax(), if the dataType: 'json' setting is specified, server must return a valid JSON formatted String, else error is thrown.

Note
Review the following statement from the official jQuery Ajax documentation – dataType settings :

“…The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown…”

To fix this, update the server side to return a JSON formatted string :


@RestController
@RequestMapping("/hosting")
public class AdminHostingController {

    @Autowired
    HostingBo hostingBo;

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateHosting(@RequestBody HostingForm hostingForm) {

        if(hostingForm!=null){
            hostingBo.update(hostingForm, UpdatedBy.WEB);
        }

        //NEED JSON format
        return "{\"msg\":\"success\"}";

        //return "success";

    }

Try again, review the browser console again, “success” event is fired.

SUCCESS:  Object {msg: "success"}

References

  1. jQuery.ajax() documentation
  2. Wikipedia : JSON
  3. Spring MVC and JSON