PHP post request always return 400 when submitted with ajax

I am trying to make a login where the username and password are passed to the API via AJAX. The problem is that he always says:

Warning: file_get_contents ( http://example.com/api/login ): Failed to open stream: HTTP request failed! Bad HTTP / 1.1 400 request in /classes/Login.php on line 20

However, if I disable jquery and just post it as plain PHP, no problem and I get a "200 OK status code" in the request.

My index.php:

    <form action="ajax/processLogin.php" method="post" name="loginform" id="loginform">
        <label for="user_name">Brugernavn</label>
        <input type="text" id="user_name" name="user_name" required>

        <label for="user_password">Kodeord</label>
        <input type="password" id="user_password" name="user_password" required>

        <input type="submit" id="login" name="login" value="Log ind">
    </form>

      

processLogin.php:

require_once "../classes/Login.php";
$login = new Login();

$params = array('brugernavn' => $_POST['user_name'], 'password' => $_POST['user_password']);

if($login->doLogin($params)){
    echo "success";
}
else{
    echo "Fail";
}

      

My Login.class.php:

    public function doLogin($params){
        $query = http_build_query($params);
        $contextData = array(
            'method' => 'POST',
            'header' => 'Connection: close\r\n' .
                        'Content-Type: application/x-www-form-urlencoded\r\n'.
                        'Content-Length: ' . strlen($query),
            'content' => $query
        );

        $context = stream_context_create(array('http' => $contextData));
        $data = file_get_contents('http://example.com/api/login', false, $context);

        $result = json_decode($data, true);

        if($result['success']){
            return true;
        }

        return false;
    }

      

My main.js file:

    $("#login").click(function(){

    var brugernavn = $("#user_name").val();
    var password = $("#user_password").val();

    if($.trim(brugernavn).length > 0 && $.trim(password).length > 0){
        $.ajax({
            url: 'ajax/processLogin.php',
            type: 'POST',
            data: 'brugernavn=' + brugernavn + '&password=' + password
        })
        .done(function(data) {
            console.log(data);
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });

    }

    return false;
});

      

I can't figure out what the problem is. This is probably something stupid that I missed

+3


source to share


1 answer


You forgot to send data with AJAX:



$.ajax({
    type: "POST",
    url: 'yoururlhere',
    data:{
        user_name: brugernavn,
        user_password: password,
    }
}).done(function(){

}).fail(function(){

}).always(function(){

});

      

+3


source







All Articles