Federick Jons Federick Jons - 1 month ago 5
AngularJS Question

Sending $http.post data in Angular. Php receive empty data

Like the title said. I want to make a $http.post request to my backend in php, but is not working. Let me show you my code at today:

function obtenerSesion() {
return $http.post(loginUrl,
{params: {
username: 'prueba123',
password: 'prueba123'}
})
.then(function(response) {
debugger;
canchas = response.data;
return canchas;
})
.catch(generarError);
}


In my PHP I have this:

.
.
22. $nombreUsuario= $_POST["username"];
23. $contrasenia= $_POST["password"];
.
.


I receive in the response status "200" but error.txt catch this when the php is execute:


Undefined index on line 22


Could you tell me, Why my php is not receiving the data?
Thanks!

//EDIT//

login.php

<?php
$response = array();

require("Db.class.php");
require("password.php");
require("jwt.php");

$settings = parse_ini_file("settings.ini.php");
$securityToken= '' . $settings["token"]. '';

$db = new Db();

$nombreUsuario= $_POST["username"]; //email o user
$contrasenia= $_POST["password"];

// $hash = password_hash($contrasenia, PASSWORD_BCRYPT);


$result = $db->query("SELECT ....);

if(count($result) == 0){
...
...


If I hardcode the $nombreUsuario='prueba123' and $contrasenia='prueba123' the php works perfect!

Answer

You're sending this object :

{"params":{"username":"prueba123","password":"prueba123"}}

instead of :

{"username":"prueba123","password":"prueba123"}

correct code :

function obtenerSesion() { 
    return $http.post(loginUrl,
             {
                 username: 'prueba123',
                 password: 'prueba123'
             })
        .then(function(response) {
            debugger;
            canchas = response.data;
            return canchas;
    })
    .catch(generarError);
}

and then read the raw input in PHP and deserialize the JSON like this :

$postdata = file_get_contents("php://input");

$request = json_decode($postdata);
$nombreUsuario = $request->username;
$contrasenia = $request->password;