TacoVox
TacoVox

Reputation: 141

POST via Ajax does not work correctly

I looked now through a various number of StackOverflow pages and other websites - but can't find the correct solution for my problem. I try to post two values over to a php page via Post:

loginframe.php:

<form class="signin">
        <input type="username" id="inputUsername" class="control" placeholder="Username" required autofocus>
        <input type="password" id="inputPassword" class="control" placeholder="Password" required>
        <div id="remember" class="checkbox">
            <label>
                <input type="checkbox" value="remember-me">Remember me
            </label>
        </div>
        <button class="btn-login" type="submit" value="login" id="btn-login">Sign in</button>
    </form>

My js:

$(document).ready(function(){
    $("#btn-login").click(function(){

        var username = $("#inputUsername").val();
        var password = $("#inputPassword").val();

        $.ajax(
        {
            type: "POST",
            url: 'login.php',
            data: {
                user: username,
                pass: password
            },
            success: function(result)
            {
                $("#result").html(result);
            }
        });
    });

});

My login.php

<?php
    if(isset($_POST['user']) && isset($_POST['pass']))
    {
        echo $_POST['user'];
        echo $_POST['pass'];
    } else {
        include 'loginframe.php';
    }

This login.php is just to check now if the data is passed. That is absolutely not the case. It always opens loginframe.php... I can't find the error - I appreciate your help! Thank you a lot.

Upvotes: 0

Views: 58

Answers (1)

Aneesh R S
Aneesh R S

Reputation: 3827

Use prevent default method.

$(document).ready(function(){
        $("#btn-login").click(function(event){

            event.preventDefault(); // this one prevents the default submission of the form

            var username = $("#inputUsername").val();
            var password = $("#inputPassword").val();

            $.ajax(
            {
                type: "POST",
                url: 'login.php',
                data: {
                    user: username,
                    pass: password
                },
                success: function(result)
                {
                    $("#result").html(result);
                }
            });
        });

    });

Upvotes: 2

Related Questions