jQuery – Ajax request return 200 OK but error event is fired?

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

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mark
5 years ago

So if you tell it to expect JSON, you better give it JSON. Why didn’t I think of that??? Anyway, thanks mkyong!

manar
3 years ago

thank you

imyzone
7 years ago

if you return number string like “123” ,I will be fine .I don’t will the reason!

ankuj
8 years ago

Gosh I spent my entire day debugging this problem, I wish I had seen your post earlier. Worked like a charm. Thank you for your tutorials and tips, they are very well done and brilliant for people like me. Great work and keep it going! 🙂

Guest
9 years ago

Thanks. It worked for me!

xBunny
9 years ago

Thanks allot! Was exactly, what I was looking for.

chocksaway.com
5 years ago

Thank you for this post. Helped me fixed things 🙂