Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple filter value parameters

I'm using this SO question to handle my filter search using checkbox.

This is the JS

$('input[type="checkbox"]').on('change', function (e) {
      var data = {},
          fdata = [],
          loc = $('<a>', { href: window.location })[0];
      $('input[type="checkbox"]').each(function (i) {
          if (this.checked) {
              if (!data.hasOwnProperty(this.name)) {
                  data[this.name] = [];
              }
              data[this.name].push(this.value);
          }
      });
      // get all keys.
      var keys = Object.keys(data);
      var fdata = "";
      // iterate over them and create the fdata
      keys.forEach(function(key,i){
          if (i>0) fdata += '&'; // if its not the first key add &
          fdata += key+"="+data[key].join(',');
      });
      $.ajax({
        type: "get",
        url: "/ajax/get",
        data: {
              "_token": "{{ csrf_token() }}",
              "fdata": fdata
            },
        success: function (response) {
          $('#d2d-results').html(response);
        }
      });
      if (history.pushState) {
          history.pushState(null, null, loc.pathname + '?' + fdata);
      }
  });

And now I try to get the value of fdata to PHP.

On PHP I get this value of variable echo $_GET['fdata'];:

discount=Y&brand=BR0006,BR0003

What I want

$discount="Y";
$brand="BR0006,BR0003";

Is it possible to do like that?

like image 251
HiDayurie Dave Avatar asked Apr 06 '26 21:04

HiDayurie Dave


1 Answers

To do what you want, you have to do two steps:

  1. parse the query string into an array:

    parse_str($_GET['fdata'], $result);
    
  2. And then, extract the array as variables:

    extract($result);
    

A few things to note:

Using extract is very insecure (and somewhat ugly). The user can put things like (for example) isAdmin=1 in the URL and the will affect your code. Basically, you cannot trust your variables anymore.

I would skip step 2 (the extract thingy), and use $result directly, for example echo $result['discount'].

like image 66
Christian Avatar answered Apr 08 '26 10:04

Christian