简体   繁体   中英

How to fix Uncaught SyntaxError: Unexpected token I in JSON?

I have a js code (in index.php ) as shown below which makes an ajax call to save.php file.

<script>
    $(function () {
        $('form').submit(function (e) {
            e.preventDefault();
            $.post({
                url: 'save.php',
                data: $(this).serialize(),
            }).done(response => {
                console.log(response);
                response = JSON.parse(response);
                if (response.message) {
                    alert(response.message);
                }
            });
        });
    });
</script>

The issue which I am facing right now with the code above is when we hit save button I am getting the following error message on the console:

VM68:1 Uncaught SyntaxError: Unexpected token I in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (index.php:1011)
    at c (jquery-3.5.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.5.1.min.js:2)
    at l (jquery-3.5.1.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery-3.5.1.min.js:2)

Here line#1011 is response = JSON.parse(response); from the js code above.

Problem Statement : I am wondering what changes I need to make in the js code above so that on hitting save button I do not get that error message on the console.

If are aware of the error and just want to ignore it/handle it use a try/catch block. That error is usually because response isn't a valid json string so JSON.parse will keep failing.

$(function () {
    $('form').submit(function (e) {
        e.preventDefault();
        $.post({
            url: 'save.php',
            data: $(this).serialize(),
        }).done(response => {
            try{
                response = JSON.parse(response);
                if (response.message) {
                    alert(response.message);
                }
            }
            catch (e) {
                //do something like alert user the request failed
                alert('Request to server failed');
            }

        });
    });

More on try/catch from mozilla.

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