0

How to securely send additional data/parameters via $.ajax for filtering?

I'm trying to send additional data/parameters via $.ajax for additional filtering of a returning json. When sending a single term, my setup looks like this:

javascript:

$.ajax({
  url: "/source.php",
  dataType: "json",
  data: {
    term: request.term
  },

Console:

GET .../source.php?term=valueA1

PHP:

$term = trim(strip_tags($_GET['term'])); 
$term = preg_replace('/\s+/', ' ', $term);

$a_json = array();
$a_json_row = array();

$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);

if(preg_match("/[^\040\pL\pN_-]/u", $term)) {
  print $json_invalid;
  exit;
}

if ($data = $mysqli->query("SELECT * FROM accounts WHERE name LIKE '%$term%' OR code LIKE '%$term%'")) {
while($row = mysqli_fetch_array($data)) {
    ...
}
}

Now, when adding/sending the additional data/parameters (if available) my setup looks like this:

$.ajax({
  url: "/source.php",
  dataType: "json",
  data: {
    term: request.term,
    tags: $('#input-newsearch-2').val()
  },

.val() of $('#input-newsearch-2') can be:

$('#input-newsearch-2').val() = 
$('#input-newsearch-2').val() = valueA1
$('#input-newsearch-2').val() = valueA1,valueA2
$('#input-newsearch-2').val() = valueA1,valueA2,valueA3

... and so on.

Console:

GET source.php?term=valueA1&tags=
GET source.php?term=valueA2&tags=valueA1
GET source.php?term=valueA3&tags=valueA1%2CvalueA2
GET source.php?term=valueA4&tags=valueA1%2CvalueA2%2CvalueA3

Is it possible to send a comma seperated array like this and how should the php look like to use tags for additional filtering (AND WHERE)?

Edit: This is not a dublicate to the referenced answer since I'm sending a possible array as second parameter. Also it doesn't answer hoe then to fetch it in php und how to use it in the query

Philipp M
  • 3,306
  • 5
  • 36
  • 90

1 Answers1

0

If you want it to be truly secure, you need to put the data inside the payload instead of in the URL or Query string.

See this relevant question: Send JSON data with jQuery

Community
  • 1
  • 1
Joshua J Wilborn
  • 526
  • 3
  • 13
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Jay Blanchard Mar 29 '17 at 18:41
  • 1
    Could you provide an example suitable to my case since I'm sending a possible array as second parameter? Also you didn't answer how I then should fetch it in php und can use it in the query – Philipp M Mar 29 '17 at 19:49
  • I'm sorry, I have never worked with php, but you just need to access the data payload instead of the params. – Joshua J Wilborn Mar 29 '17 at 19:54