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;
}
NULL
? I don't see anything in your AJAX code where you actually log or show the data which was returned by AJAX, so I can't work out how you are determining that it's null. If you're seeing thatNULL
as a result of a different HTTP request (e.g. the one where your page is first loaded, or something like that), then that's not at all surprising because POST variables only exist in the request where they were actually sent. If you look in your browser's Network tool at the AJAX request, you can see in the Response tab what PHP actually returns from that onesuccess: function(data) { console.log(data); }
In theajax
success
method?var_dump($_POST['filterAdvertentienummer']); // = NULL
echo $_POST['filterAdvertentienummer']; // = empty string
when I get the data in PHP
...again, how do you know? You didn't say where or when you're seeing that output from PHP, which is what we asked you.What I do afterwards with the data after succes or error does not matter since it is not even in the PHP
...you seem to have misunderstood how AJAX works, then. When you send an AJAX request, the data is sent (asynchronously, in the background) to the PHP script mentioned in the "url" option. Any output from that PHP script (e.g. from anecho
orvar_dump
statement) is sent back as the response to the AJAX request. Because it's an AJAX request from Javascript, that response is given back to you in thesuccess
variable in your JS code. It does not show directly on screen or anything...