simple-php-router icon indicating copy to clipboard operation
simple-php-router copied to clipboard

Method of a controller does not receive the data by POST

Open LuisEstrada7 opened this issue 2 years ago • 7 comments

The route works correctly but it seems that the data is not sent to my method since it does not let me use the values.

Project: https://github.com/LuisEstrada7/prueba-simple-php-router

index.php

require_once 'vendor/autoload.php';
use Pecee\SimpleRouter\SimpleRouter;
require_once 'app/Controllers/persona/personaController.php';
require_once 'routes.php';
require_once 'helpers.php';
SimpleRouter::setDefaultNamespace('app\Controllers');
SimpleRouter::start();

routes.php

SimpleRouter::group(['prefix' => '/persona'], function () {
    SimpleRouter::post('/insertUpdate', 'persona\personaController@insertUpdate');
});

Use fetch JS to do the queries.

app.js

export const cargador__ = 'before-page';
export const fetch_ = (_url,_type,_data) => {
    return fetch(_url, {
        method: _type,
        body: JSON.stringify(_data),
        headers:{ 'Content-Type': 'application/json' }
    }).then(res => res.json())
    .then(response => response);
};

Persona.js

import { cargador__, fetch_get, fetch_ } from "/public/assets/js/app.js";
document.addEventListener("DOMContentLoaded", async function(event){
const tbPersona = document.getElementById('tabla-personas'),
        btnNew = document.getElementById('btn-new'),
        modalInserUpdate = document.getElementById('modal-insertUpdate'),
        mdInsertUpdate = new bootstrap.Modal(modalInserUpdate, {backdrop: 'static', keyboard: false}),
        btnEditPersona = 'btn-edit-persona',
        btnSave = document.getElementById('btnSave'),
        id = document.getElementById('id'),
        txtDni = document.getElementById('dni'),
        txtPaterno = document.getElementById('apePaterno'),
        txtMaterno = document.getElementById('apeMaterno'),
        txtNombres = document.getElementById('nombres'),
        txtEmail = document.getElementById('email'),
        txtLenguaje = document.getElementById('lenguaje'),
        cboFase = document.getElementById('cboFase'),
        txtEdad = document.getElementById('edad'),
        txtComprendido = document.getElementById('comprendido');
btnSave.addEventListener('click', async () => {
        document.getElementById(cargador__).setAttribute('style', 'display:flex');
        const datos = {
            id: isNaN(parseInt(id.value.trim())) ? null : parseInt(id.value.trim()),
            dni: txtDni.value,
            paterno: txtPaterno.value,
            materno: txtMaterno.value,
            nombres: txtNombres.value,
            email: txtEmail.value,
            lenguaje: txtLenguaje.value,
            fase: cboFase.value,
            edad: txtEdad.value,
            comprendido: txtComprendido.value,
        };
        console.log(datos);
        const resultado = await fetch_('/persona/insertUpdate', 'POST', datos);
        console.log(resultado);
        document.getElementById(cargador__).setAttribute('style', 'display:none');
    });
});

controller:

namespace app\Controllers\persona;
require_once $_SERVER['DOCUMENT_ROOT'].'/app/Models/persona/Persona.php';
use Persona;
class personaController{
      public function insertUpdate(){
          $id = isset($_POST['id']) ? $_POST['id'] : null;
          $id = $id > 0 ? $id : null;
          $persona = new Persona();
          $persona->setId($id);
          $persona->setDni($_POST["dni"]);
          $persona->setNombres($_POST["nombres"]);
          $persona->setApePaterno($_POST["paterno"]);
          $persona->setApeMaterno($_POST["materno"]);
          $persona->setCorreo($_POST["email"]);
          $message = $persona->insertUpdate();
          $personas = $persona->getAll();
          $resultado = [$message, $personas];
          return json_encode($resultado);
      }
}

Can someone please tell me where the error is? Are you implementing the library wrong?

sent values:

{
  comprendido: "on",
  dni: "08601381",
  edad: "20",
  email: "[email protected]",
  fase: "3",
  id: null,
  lenguaje: "php"materno: "mate",
  nombres: "nom",
  paterno: "ape"
}

network :

Notice: Undefined index: dni in C:\xampp\htdocs\uni\practicantes\ejemplos\luis\app\Controllers\persona\personaController.php on line 27

Notice: Undefined index: nombres in C:\xampp\htdocs\uni\practicantes\ejemplos\luis\app\Controllers\persona\personaController.php on line 28

Notice: Undefined index: paterno in C:\xampp\htdocs\uni\practicantes\ejemplos\luis\app\Controllers\persona\personaController.php on line 29

Notice: Undefined index: materno in C:\xampp\htdocs\uni\practicantes\ejemplos\luis\app\Controllers\persona\personaController.php on line 30

Notice: Undefined index: celular in C:\xampp\htdocs\uni\practicantes\ejemplos\luis\app\Controllers\persona\personaController.php on line 31

LuisEstrada7 avatar Jan 07 '23 05:01 LuisEstrada7

Hello,

I do not see an error directly. Can you show me the request body in the network tab of the browser so that I can reconstruct everything?

Also maybe try to use the InputHandler of the library.

~ Marius

DeveloperMarius avatar Jan 07 '23 07:01 DeveloperMarius

@DeveloperMarius

Add the network to the question, can you tell me where is the InputHandler?

LuisEstrada7 avatar Jan 07 '23 17:01 LuisEstrada7

Hey,

I will take a closer look at your issue tomorrow.

You can find the input handling in the documentation under input & parameters, I think.

This would be the best in your case:

# Only match specific keys
$values = input()->all([
    'company_name',
    'user_id'
]);

~ Marius

DeveloperMarius avatar Jan 07 '23 17:01 DeveloperMarius

@DeveloperMarius Thanks! that worked for me.

    public function insertUpdate(){
        $values = input()->all();
        var_dump($values['dni']);
        echo "<br>";
        var_dump($values);exit;
    }

LuisEstrada7 avatar Jan 07 '23 17:01 LuisEstrada7

Great!

This project is no longer maintained. When you want PHP 8.x support, input validation etc. check out my fork https://github.com/DeveloperMarius/simple-php-router It has a few breaking changes but all pull requests & issues are solved there.

~ Marius

DeveloperMarius avatar Jan 07 '23 17:01 DeveloperMarius

Great!

This project is no longer maintained. When you want PHP 8.x support, input validation etc. check out my fork https://github.com/DeveloperMarius/simple-php-router It has a few breaking changes but all pull requests & issues are solved there.

~ Marius

But it seems abandoned.

AlexJMcloud avatar Oct 20 '23 19:10 AlexJMcloud

Hey,

I replyed to your question. I give my best to be up to date with the issues but I cannot always reply quickly.

~ Marius

DeveloperMarius avatar Oct 24 '23 10:10 DeveloperMarius