Home > Software engineering >  Uncaught SyntaxError: Invalid or unexpected token in ajax call
Uncaught SyntaxError: Invalid or unexpected token in ajax call

Time:05-03

I have a form which looks like this:

<form id="login_form"  method="post" style="width: 450px;">
        <h1 >LOGIN</h1>

        <div id="error_box"  role="alert"> </div>

        <div >
            <label for="username" >User name</label>
            <input type="text"  name="username" id="username">
        </div>

        <div >
            <label for="password" >Password</label>
            <input type="password" name="password"  id="password">
        </div>

        <button type="submit" >LOGIN</button>
</form>

When I click the login button I want to check if the given username and password are in the database. If they are, I want to move to a different page. If they are not, I add an error message text to the above div with ID "error_box" and make it visible (it is initially invisible). This is how the jquery code looks like:

<script>
        $(document).ready(function () {
            const errorBox = $("#error_box");
            errorBox.hide();
            $("form").on('submit', function (event) {
                errorBox.empty();
                $.ajax({
                    type: "GET",
                    url: "controller/controller.php",
                    data: {action: "checkLogin", username: "<?=$_POST['username']?>", password: "<?=$_POST['password']?>"},
                    success: function (jsonResponse) {
                        const result = $.parseJSON(jsonResponse)["result"];
                        if (result === "success") {
                            window.location.href = "home.php";
                        } else {
                            errorBox.show();
                            errorBox.append(result);
                        }
                    }
                });
                event.preventDefault();
            });
        })
</script>

The function checkLogin from controller.php will return a json with one field, "result". If the username/password combination is correct, it will return {"result": "success"}. If the username/password combination is incorrect, it will return {"result": <error_message>}, where <error_message> can be something like "You cannot enter an empty username". You get the idea.

The problem is that I get an "Uncaught SyntaxError: Invalid or unexpected token". The browser says it is at the line where I have type: "GET" in the ajax call. This exception also makes the div which will have the error message to not be hidden, so I have an empty red box above the username and password fields (and it shouldn'y be there, it should only appear after the user clicks on the login button with invalid username/password). If I delete the ajax call I don't have the exception anymore and the div gets hidden. I don't know how to solve it/why I get this exception. I tried specifying the dataType attribute in the ajax call as 'json', but that still didn't work. I tried changing the ajax call to a $.getJSON() call and I got the same exception (I know they do the same things, but I'm getting desperate). What's wrong?

CodePudding user response:

There is php syntax in your ajax form and the problem is in those lines where you get the username and password from the inputs. Try to get the values of inputs from using jquery or javascript.

And your script should be like this

<script>
    $(document).ready(function () {
        const errorBox = $("#error_box");
        errorBox.hide();
        $("form").on('submit', function (event) {
            errorBox.empty();
            $.ajax({
                type: "GET",
                url: "controller/controller.php",
                data: {action: "checkLogin", username: $('#username').val(), password: $('#password').val()},
                success: function (jsonResponse) {
                    const result = $.parseJSON(jsonResponse)["result"];
                    if (result === "success") {
                        window.location.href = "home.php";
                    } else {
                        errorBox.show();
                        errorBox.append(result);
                    }
                }
            });
            event.preventDefault();
        });
    })
  • Related