skip to Main Content

Whenever I submit a from using jquery ajax to an PHP api the form is not submitting to the required post request handler. But when I submit the form basically, I mean without using an javascript or jquery the form is submit and it is redirecting to a php page with json response.

Note No problems with CORS here the CORS are fine as I have allowed cross-site requests in the api.

Below is my login.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./assets/css/style.css">
    <script src="./assets/js/jquery-3.4.1.min.js"></script>
    <title>User Login Page</title>
</head>

<body>
    <div class="header">
        <h2>Login</h2>
    </div>

    <form action="http://localhost/auth-app/server.php" method="post">
        <div class="input-group">
            <label for="">Email</label>
            <input type="email" name="email" id="email" required>
        </div>
        <div class="input-group">
            <label for="">Password</label>
            <input type="password" name="password" id="password" required>
        </div>
        <div class="input-group">
            <input type="submit" value="Login" name="login" class="submit-btn">
        </div>
        <p>
            Not yet a member? <a href="register.html">Register</a>
        </p>
    </form>

    <script>
        $(document).ready(function () {
            // submit login form with ajax
            $('form').submit(function (event) {
                /* stop form from submitting normally */
                event.preventDefault();
                $(".submit-btn").click(function () {
                    $.post("http://localhost/auth-app/server.php", {
                        email: $('#email').val(),
                        password: $('#password').val()
                    },
                        function (data, status) {
                            const json = $.parseJSON(data);
                            console.log("Data: " + typeof(json) + "nStatus: " + status);
                        });
                });
            });
        });


    </script>
</body>

</html>

Note What I want is to be able to submit the form to the required PHP post request handler function using jquery ajax.

Below is my server.php api file.


$errors = array();

// login
if (isset($_POST['login'])) {
    $email = $db->real_escape_string($_POST['email']);
    $password = $db->real_escape_string($_POST['password']);

    if (empty($email)) {
        array_push($errors, 'Email is required');
    }
    if (empty($password)) {
        array_push($errors, 'Password is required');
    }

    if (count($errors) == 0) {

                // log user in
                $data = ['success_login' => 'true'];
                header('Content-type: application/json');
                echo json_encode(null);
        } else {
            array_push($errors, 'The email or password is incorrect');
            // after entering wrong credentials
            $data = ['success_login' => 'false'];
            header('Content-type: application/json');
            echo json_encode($data);
        }
}

In debug console I’m getting the error bellow.
Note this is just proof that the post request is not reaching the php post request handler in the in the api file.

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

What I’m expecting to get in the console is json data like below:

success_login   "true"

!IMPORTANT INFO:
I’m not very experienced with php but I have noticed that when submitting form without using any javascript eg jquery or ajax the form submits successfully because the name of the submit button eg <input type="submit" value="Login" name="login"> is the same as the name inside $_POST['login']. But when submitting form using ajax technically you don’t use that button to submit.

So how do I solve this problem? Thank you posted with Love.

2

Answers


  1. Try something like below code

          $(document).ready(function () {
            $('form').submit(function (event) {
            event.preventDefault();
            $(".submit-btn").click(function () {
    
             name: $('#email').val(),
             password: $('#password').val()
    
            $.ajax({
                type: 'post',
                url: 'http://localhost/auth-app/server.php',
                data: {
                    name: name,
                    password : password,
                    action: 'login'
                },
                success: function(response) {
    
                }
            })
        });
        });
        });
    
    Login or Signup to reply.
  2. You do not need to declare the click button event as you are already using the form submit button event. Also, add the login key as the parameter value in $.post, as you are checking it’s isset value in login.php file.

    Also, note that there is extra closes braces “}” in your login.php file

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search