Hi all,

I would like to get some help with something i would like to see working. It's hard to explain but i'll give it my best shot.

I want to retrieve the result from a DB by selecting multiple selections in 2 or 3 or even more select boxes.

To illustrate i made it visual:

[IMG][/IMG]

For example if i select

Mona Lisa, M. Angelo, Rembrandt and france i would like to see the pictures of all in the db except for dunno.jpg

I have tried it with the example on w3schools with AJAX and database. But it's not even wothy posting it here. I have searched for such a script over the internet, but nothing comes near.

So I hope this Forum can help me out on this one. I would be very thankfull.

Dani AI

Generated

This thread shows the core issue: each select's inline handler only sends that one control's value. As pointed out, every change needs the current selections from all boxes. The practical approach is to (1) collect all selected values from each select when any select changes, (2) send them together to the server (prefer POST/JSON or URL-encoded POST), and (3) have the server build a parameterized query (IN lists) so you can match multiple choices safely.

Example client-side flow (attach a debounced change listener to each select, gather selected values, POST JSON, render returned rows):

/* attach class="filter" to each select */
const debounce = (fn, wait=250) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(()=>fn(...a), wait); }; };

function collectAndSend() {
  const selects = document.querySelectorAll('select.filter');
  const payload = {};
  selects.forEach(s => {
    const vals = Array.from(s.options).filter(o => o.selected).map(o => o.value);
    if (vals.length) payload[s.id || s.name] = vals;
  });
  fetch('getphoto.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(payload),
    cache: 'no-cache'
  })
  .then(r => r.json())
  .then(rows => {
    document.getElementById('txtHint').innerHTML =
      rows.map(r => `<img src="${r.photo}" width="80" style="padding:20px;border:0">`).join('');
  });
}

document.querySelectorAll('select.filter').forEach(s => s.addEventListener('change', debounce(collectAndSend)));

Server-side notes: accept JSON, decode it, and build a prepared statement with dynamic placeholders for each IN list (do not implode values directly into SQL). Example idea using PDO:

<?php
$data = json_decode(file_get_contents('php://input'), true) ?? [];
// build WHERE parts like "artist IN (:artist_0,:artist_1)" and bind params
// prepare, execute, echo json_encode($rows);
?>

Troubleshooting and best practices: validate/cast incoming values, use prepared statements to avoid SQL injection, limit results and add indexes, use the network inspector to verify payloads, and debounce changes so rapid clicks do not flood the server. If selections should be OR across different selects instead of AND, combine WHERE parts with OR instead of AND. This approach fixes the single-value problem saw and answers 's question about when to send (on change is fine if debounced).

Recommended Answers

All 3 Replies

When you want to send an Ajax request? On each selection or after all the selection.

What exactly you want to know? Give us little more details so that we can help u.

Hi thanks for willing to help me. I have 3 scripts. And i manage to get result from just 1 selection. I think what i need is a javascript that remembers all the selection.

I want to send with each change i make with the selection.

These are my scripts.

testdb.php

<html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<script src="selectResult.js"></script>
</head>
<body>

<form> 
<table>
  <tr>
    <th>box1</th>
    <th>box2</th>
    <th>box3</th>
  </tr>
  <tr>
    <td>
      <select name="box1" onchange="showResult(this.value)" multiple size="4">
      <option value="1">value1</option>
      <option value="2">value2</option>
      <option value="3">value3</option>
      <option value="4">value4</option>
      <option value="5">value5</option>
      </select>
    </td>
    <td>
      <select name="box2" onchange="showResult(this.value)" multiple size="4">
      <option value="1">value1</option>
      <option value="2">value2</option>
      <option value="3">value3</option>
      <option value="4">value4</option>
      </select>
    </td>
    <td>
      <select name="box3" onchange="showResult(this.value)" multiple size="4">
      <option value="1">value1</option>
      <option value="2">value2</option>
      <option value="3">value3</option>
      <option value="4">value4</option>
      </select>
    </td>
  </tr>
  
</table>

</form>

<p>
<div id="txtHint"><b>Photos will be showed here.</b></div>
</p>
</body>
</html>

// JavaScript Document
var xmlHttp
function showResult(str)
{ 
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="getphoto.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
 } 
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

and the last is for the DB

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', '****', '****');
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db("designconsumer", $con);

$sql="
      SELECT photo FROM db         
      WHERE result = '".$q."'    
      limit 0, 50
";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
 {

 echo "<img src=\"". $row['photo'] ."\" width=\"80\" style=\"padding: 20px; border: 0px solid #000;\">";

 }

mysql_close($con);
?>

As your code currently stands, showResult(this.value) is only going to use the value of the clicked select box. Each time you click one of the selects, it will only send its value to the javascrit function and ignore the rest. I assume you want the values from all three to be taken into account every time one of them is clicked.

You will need the values passed to your showResult function to include the values from all three - probably use onClick="getElementById('selectboxid').value for all three and concatenate them in some way that your getphoto.php page will be able to interpret.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.