When sending data to an ajax post call I get "NULL" returned. I am sending a lot more data (which all works), but left it out of the snippet to make it more clear.
When I log the var in my console, it shows up. When I check the network tab if the data is properly sent, it shows up. When I var_dump the $_POST in PHP it returns NULL.
Jquery
function get_cars_ajax() {
var filterAdvertentienummer = 119005595; // is number
$.ajax({
type: 'POST',
url: '/wp/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
'action' : 'get_cars_filter',
'filterAdvertentienummer ' : filterAdvertentienummer,
},
success: function(data) {
if(data != '') {
// DO SOMETHING
} else {
// DO NOTHING
}
},
error: function(data) {
console.log(data);
}
}
PHP
function get_cars_filter() {
global $post;
$context = Timber::get_context();
var_dump($_POST['filterAdvertentienummer']); // = NULL
echo $_POST['filterAdvertentienummer']; // = empty string
if (isset($_POST['filterAdvertentienummer'])) {
$advertentienummer = $_POST['filterAdvertentienummer'];
} else {
$advertentienummer = "";
}
$queryList = '?skip='.$current_page.'&limit='.$limit.'&sort='.$sort.'&order='.$order;
if ($advertentienummer != "") {
$queryList = $queryList . "&advertentienummer=" . $advertentienummer;
} else {
var_dump($advertentienummer);
}
$args = array(
'headers' => array(
'accept' => 'application/json'
)
);
$results = wp_remote_retrieve_body(wp_remote_get('http://IP/cars'.$queryList, $args));
return $results;
}
CodePudding user response:
I noticed a mistake in your ajax code.
Your code line:
'filterAdvertentienummer ' : filterAdvertentienummer,
you have added one space in the variable name so it's not gonna be readable by PHP.
Modified code :
'filterAdvertentienummer' : filterAdvertentienummer
Now PHP will read this variable as a string. You can convert strings in int with PHP.