Home > Enterprise >  jQuery.ajax int is being sent but $_POST returns NULL
jQuery.ajax int is being sent but $_POST returns NULL

Time:10-27

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;
}

network tab clearly showing it does pass the data

var_dump and echo show empty var

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.

  • Related