Estoy tratando de pasar el valor seleccionado con ajax al controlador php pero no funciona. este es mi codigo
function prodType() { $("#productType").change(function(){ let value = $("#productType").val(); $.ajax({ url: "<? echo URLROOT. '/AddProduct'?>", type:"GET", //not sure if this should be get or post data:{ "optionValue": value }, success: function(response){ } }); });Estoy seguro de que está obteniendo el valor, pero no lo está pasando con éxito al controlador.
este es mi controlador
public function index(){ $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); if($_SERVER["REQUEST_METHOD"]=="POST"){ ... } /*If request method == Get, load view */ else{ $type = $_POST['optionValue']; //trying to get the value here $typeClass = ucfirst($type); new Display(new $type); var_dump($type); //getting null here $this->view('add'); } }esta es mi vista
<select id="productType" name="type" onChange="prodType();" required> <option value="" hidden>Select type</option> <option value="DVDType" >DVD</option> <option value="BookType" >Book</option> <option value="FurnitureType">Furniture</option> </select> Cambié el type de GET a POST y todavía no funcionó. Estoy pensando que tal vez mi controlador debería ser este en su lugar
public function index(){ $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); if($_SERVER["REQUEST_METHOD"]=="POST"){ ... $type = $_POST['optionValue']; //trying to get the value here $typeClass = ucfirst($type); new Display(new $type); var_dump($type); //getting null here } /*If request method == Get, load view */ else{ $this->view('add'); } } (Obteniendo el valor de ajax cuando el método de solicitud del servidor es POST). Dado que el valor solo se puede establecer después de que se haya cargado la página. Pero luego necesito que el valor sea antes de que se envíe el formulario, por lo tanto, es posible que $_POST no lo detecte. ¿Qué me estoy perdiendo?
Como se documenta , la matriz $_POST contiene las "variables pasadas al script actual a través del método HTTP POST".
Por lo tanto, debe cambiar su llamada ajax a una solicitud POST:
function prodType() { $("#productType").change(function(){ let value = $("#productType").val(); $.ajax({ url: "<? echo URLROOT. '/AddProduct'?>", type:"POST", data:{ "optionValue": value }, success: function(response){ } }); });