I am trying to pass selected value with ajax to php controller but its not working. This is my code
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){
}
});
});
I'm sure its getting the value but it is not successfully passing it to the controller.
This is my controller
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');
}
}
This is my view
<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>
I changed type from GET to POST and it still didn't work. I am thinking maybe my controller should be this instead
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');
}
}
(Getting the value from ajax when the Server request method is POST). Since the value can only be set after the page has been loaded. But then i need the value to be before the form is submitted hence $_POST might not catch it. What am i missing?
As documented, the $_POST array contains the "variables passed to the current script via the HTTP POST method".
Therefore, you should change your ajax-call to a POST-request:
function prodType() {
$("#productType").change(function(){
let value = $("#productType").val();
$.ajax({
url: "<? echo URLROOT. '/AddProduct'?>",
type:"POST",
data:{
"optionValue": value
},
success: function(response){
}
});
});