Angular factory to insert data into the database

Asked

Viewed 186 times

2

How do I create a function, in Factory, to enter data in the database? I have it:

.factory('pegaContas', ['$http', function($http) {
    var _getContasEntrada = function(id_empresa) {
        return $http.post("php/index.php", id_empresa);
    };

    var _setContasEntrada = function(conta) {
    }

    return {
        getContasEntrada: _getContasEntrada
        setContasEntrada: _setContasEntrada
    }
}])

And my function/method in php data insertion is in a class:

    <?php
    function insereContaEntrada($id_empresa, $cat, $subcat, $val, $forPag, $data){
        $pdo = conectar();
        $val = floatval(str_replace(',', '.', str_replace('.', '', $val)));

        if($data == ''){
            $data = date("Y-m-d");
        }

        $this->insereDadosEntrada=$pdo->prepare(
            "INSERT INTO entrada (id_entrada, id_empresa, categoria, subcategoria, valor, forma_pagamento, data) 
             VALUES (?, ?, ?, ?, ?, ?, ?)");
        $this->insereDadosEntrada->bindValue(1, NULL);
        $this->insereDadosEntrada->bindValue(2, $id_empresa);
        $this->insereDadosEntrada->bindValue(3, $cat);
        $this->insereDadosEntrada->bindValue(4, $subcat);
        $this->insereDadosEntrada->bindValue(5, $val);
        $this->insereDadosEntrada->bindValue(6, $forPag);
        $this->insereDadosEntrada->bindValue(7, $data);
        //$this->insereDadosEntrada->execute();
        try {
            $this->insereDadosEntrada->execute();
            echo "Cadastro efetuado com sucesso!";
        } catch (Exception $e) {
            print_r($this->insereDadosEntrada->errorInfo());
        }
    }
?>

I want to call that method at the angle.

1 answer

2


Well, first you need to inform php which function you want to call. The method I use for this, is through a action, where my link on .factory would look like this:

var _getContasEntrada = function(id_empresa) {
   return $http.post("php/index.php?action=insereContaEntrada",id_empresa).then( 
        function(res) { 
            console.log(res); //Verifica o que o php está retornando
            return res.data;
        },
        function(err) {alert(feedbackError);}
    );
};

Already in the php, use a switch to determine the types of action which can be called in this way:

switch($_GET['action']) {
    case 'insereContaEntrada': insereContaEntrada();
    break;
}

function insereContaEntrada()....

The data process, is done differently (at least for me). I search the data coming through the function and do the decode from it, because it will come in the JSON model, this step is at your discretion (I believe). But right at the beginning of the function, use:

$result = json_decode(file_get_contents("php://input"));

This way, you will convert the incoming data into an array that you can work on better. Or, just use the code file_get_contents("php://input") to take the raw dice.

Ps.: I’m not very good in the PHP area, so I might be wrong about using only the last code, but I think now you have an idea of how it works.


Edited:

Now that I’ve noticed, your code has some syntax errors, I don’t know if it was just here or in your code as well, but it must be like this:

.factory('pegaContas', ['$http', function($http) {
    var _getContasEntrada = function(id_empresa) {
        return $http.post("php/index.php", id_empresa);
    };

    var _setContasEntrada = function(conta) {
    };

    return {
        getContasEntrada: _getContasEntrada,
        setContasEntrada: _setContasEntrada
    }
}])

In the Return block, the name with the prefix _ It only serves to identify which is which. In this case, the prefixed name is the name you use within a controller to call a function within Factory. The prefixed name is to identify which function within Factory should be called. Only one best practice for you to organize better. And you should always have a comma separation, except the last definition.

  • Thanks, I’ll try it...

  • @Gustavosevero edited my answer. As you are using php, often the error is not in Angular, so I recommend using Factory’s Return in that way, so you can see in the console what is happening in php.

  • Right..........

  • Nothing goes inside this: var _setContasEntrate = Function(account) { }; ?

  • I think not, these functions have no relation to each other. The _setContasEntrate function would be used to call another php function. If not your case, it can be deleted

Browser other questions tagged

You are not signed in. Login or sign up in order to post.