Home > Net >  JSON Parse error when submitting AJAX post to Spring Boot Controller using Thymeleaf
JSON Parse error when submitting AJAX post to Spring Boot Controller using Thymeleaf

Time:09-09

I have a form that I am submitting using AJAX:

var formData = JSON.stringify($('#supportrequest').serializeArray());
        
        $.ajax({
            type: "POST",
            url: "/updatesupportrequest?bugid="   $('#requestnum').val(),
            data: formData,
            success: function(){
                    console.log("success");
                },
            error: function(xhr, status, error) {
                console.log(xhr);
                console.log(status);
                console.log(error);
            },
            complete: function(){
                console.log("complete");
            },
            dataType: "json",
            contentType : "application/json"
        });

This is picked up by my Spring Boot controller:

@PostMapping("/updatesupportrequest") // Called by the form
    public String createSupportRequest(@RequestParam(name = "bugid") int bugid, @RequestBody String requestBody,
            Model model) {
        
        System.out.println(bugid);

        DatabaseWriteResponse response = writeToDatabaseService
                .writeToDatabase(WriteToDatabaseService.PROCEDURE_UPDATESUPPORTREQUEST, requestBody);

        System.out.println(response.getResponse());
        
        if (response.getResponse().equals(DatabaseWriteResponse.SUCCESS)) {         
            return "supportrequest";
        }
        else {              
            model.addAttribute("response", response.getResponse());
            model.addAttribute("errorMsg", response.getMsg());

            return "error";
        }

    }

The actual saving of the data works just fine. The problem is that the controller returns the "supportrequest.html" page. AJAX then throws a parse error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Looking at the xhr.responseText, we get the page back:

responseText: "<!--\r\n TODO\r\n - Dev page has some different fields \r\n\r\n\r\n -->\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n<head>\r\n<title>Support Center</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; 

I either need the page to redirect properly (which works fine on Get, just not Post) or to be able to return an empty JSON string and trigger the AJAX success function. I don't particular care which - I can handle the result either way. I just can't get either option to work. What am I doing wrong?

CodePudding user response:

If you want to return JSON in a @Controller class, then annotate the return type of the method with @ResponseBody.

  • Related