Solved

Fill listbox, when clicked on onother listbox in PHP

Posted on 2013-12-02
16
504 Views
Last Modified: 2013-12-20
Hi!

Have 2 listboxes, like this code:

<!-- Start Organisasjon -->
  <tr>
  <td  class="rapport1_del3" align="right">Organisasjon:</td>
  <td align="left">
      <select id="recipient" name="organisasjon" class="selmenu">
                  <?php

                     $query = "SELECT OrganisationName FROM {$table5} WHERE UserID='{$brukerID}'";
//execute the SQL query and return records
                     $resultraptmp = sqlsrv_query( $conn,$query); 
// Parameter for rapport
                     while($row3 = sqlsrv_fetch_array($resultraptmp)){

                        $navnorganisasjon = $row3['OrganisationName'];
            
                        echo "<option ";
                        if($organisasjon == $navnorganisasjon) echo ' selected="selected"';
                        echo ">$navnorganisasjon</option>"; 
                  ?>
                   
    
<?php
}
?>    
    </select>
  </td>
  </tr>
<!-- END Organisasjon -->


<!-- Start Brukere -->
	<tr>
	<td  class="rapport1_del3" align="right">Bruker:</td>
	<td align="left">
  	  <select id="recipient" name="brukere" class="selmenu">
  						<option>Alle brukere</option>
                  <?php

                     $query = "SELECT Name FROM {$table2} WHERE Organisation='{$kundeid}'";
//execute the SQL query and return records
                     $resultraptmp = sqlsrv_query( $conn,$query); 
// Parameter for rapport
                     while($row3 = sqlsrv_fetch_array($resultraptmp)){

                        $navnbruker = $row3['Name'];
						
						            echo "<option ";
                        if($brukere == $navnbruker) echo ' selected="selected"';
                        echo ">$navnbruker</option>"; 
                  ?>
                   
	  
<?php
}
?>		
	  </select>
	</td>
	</tr>

Open in new window


If a user click on a organisation from the first list -> name="organisasjon"
It must fill the listbox2, with new data depended on listbox1 value.

How do i do this ?
0
Comment
Question by:team2005
  • 8
  • 8
16 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Because the first listbox will change in the browser, not on the server, you will need to fire a javascript function to make an AJAX request back to the server to get the data for the second listbox. With jQuery this is fairly straight forward:

$('#firstListBox').change(function() {
   $.ajax({
      url: 'yourScript.php',
      type: 'post',
      data: { firstValue : $(this).val() }
   })
   .done(function(response) {
      $('#secondListBox).html(response);
   });
});

Open in new window

When the first list box changes (a select with an ID of firstListBox) a request is made to a file called yourScript.php on the server. The value of the first list box is passed to this scripts as $_POST['firstValue'] so you can query your database using that value. Your script would then build the HTML for the second list box (the <option> tags) and inject it back into a SELECT with an ID of #secondListBox.

This is a broad overview as I don't know how much you know jQuery, so come back if you have questions
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

Tryed to implemen t your code like this:

<script type="text/javascript"
$('#firstListBox').change(function() {
   $.ajax({
      url: 'yourScript.php',
      type: 'post',
      data: { firstValue : $(this).val() }
   })
   .done(function(response) {
      $('#secondListBox).html(response);
   });
});
</script>

Open in new window


But it somthing wrong, and can you please explane how this works ?
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
If you read my previous comment, it will explain how it works.

Make sure you include the jQuery library in the HEAD of your document
Wrap the jQuery code in a $(document).ready() block
Explain which bits you're struggling with
Show us your HTML
Show us your yourScript.php file
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

Not used jquery so mutch, have tryed this code now, but somthing is not right

Can you please correct the source for me, rhank you

<script type="text/javascript">
  
  $(document).ready(function() {
 $('#firstListBox').change(function() {
     $.ajax({
      url: 'yourScript.php',
      type: 'post',
      data: { firstValue : $(this).val() }
   })
   .done(function(response) {
      $('#secondListBox).html(response);
   });
});
  });
</script>

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
As I said in my previous comment - I'll need to see your HTML document and your yourScript.php file.

As it stands, there's nothing wrong with your jQuery code, but it will only work if your HTML file and the yourScript.php file are correct
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

Make this testfile now, but it dosent fill listbox 2 ?

<?php
  error_reporting(E_ALL);
  ini_set("display_errors", 1);

  require_once('RAY_EE_config.php');
  require_once('Connect_databse.php');
  $table1 = 'SHOW_UserOrganisation';

?>

<script type="text/javascript">

function GetSubCategories(){
   var orgnavn = document.getElementById("organisasjon").value;

   $.ajax({
            url : 'selectbrukere.php',
            type : 'POST',
            data : "organisasjon=" + orgnavn ,
            success : function (data) {
                if (resp.status) {
                    $("#result").html(data);
                } 
            }
        });
}

</script>


<table>
<!-- Start Organisasjon -->
  <tr>
  <td  class="rapport1_del3" align="right">Organisasjon:</td>
  <td align="left">
      <select id="organisasjon" name="organisasjon" class="selmenu" onclick="GetSubCategories()">
                  <?php

                     $query = "SELECT distinct(OrganisationName) FROM {$table1}";
//execute the SQL query and return records
                     $resultraptmp = sqlsrv_query( $conn,$query); 
// Parameter for rapport
                     while($row3 = sqlsrv_fetch_array($resultraptmp)){

                        $navnorganisasjon = $row3['OrganisationName'];
            
                        echo "<option ";
                        if($organisasjon == $navnorganisasjon) echo ' selected="selected"';
                        echo ">$navnorganisasjon</option>"; 
                  ?>
                   
    
<?php
}
?>    
    </select>
  </td>
  </tr>
<!-- END Organisasjon -->

<!-- Start Brukere -->
  <tr>
  <td  class="rapport1_del3" align="right">Bruker:</td>
  <td align="left">
      <select id="brukere" name="brukere" class="selmenu">
            
      </select>
  </td>
  </tr>
<!-- END Brukere -->
</table>

Open in new window


********* selectbrukere.php *****************
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

echo "BRUKER";
die();

require_once('RAY_EE_config.php');
require_once('Connect_databse.php');
$table1 = 'SHOW_UserOrganisation';

$orgnavn = $_GET["organisasjon"];
// change the query so that the column names match your subcategory table
$query="select Name from {$table1} where OrganisationName=". $orgnavn;
$result = sqlsrv_query( $conn,$query); 
?>

<select name="brukere" id="brukere">
<?php
while($row3 = sqlsrv_fetch_array($result)){

             $navnbruker = $row3['Name'];
            
             echo "<option ";
             echo ">$navnbruker</option>"; 
?>
</select>

Open in new window



Why isent this work ?
I echo ->  BRUKER..  to see if this php file is called , it is not
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Still only seeing part of your page, so still guessing a little here.

Firstly, a couple of things wrong with your javascript.  When using jQuery it's considered best-practice to bind the events to the elements when the page loads, so you no longer use onclick="someFunction()". Also, you should be binding to the change() event, not the click().

Once the AJAX call is finished you are trying to drop the results into a #result element, but you don't seem to have one. As you want to populate the dropdown, I'm guessing that should be #brukere.

Here's the code you need. This should go in the head of your document, after the jQuery library script:

$(document).ready(function() {
$('#organisasjon').change(function() {
	$.ajax({
		url : 'selectbrukere.php',
		type : 'POST',
		data : { organisasjon : $(this).val() },
		success : function (data) {
			$("#brukere").html(data);
		}
	});
});
});

Open in new window

Your PHP script currently outputs BRUKER and stops! (lines 5 and 6). You need to remove them to allow your script to run.

You are using POST to send the data to the server, not GET, so in your script change line 12 to this:

$orgnavn = $_POST["organisasjon"];

Now because the #brukere element in your HTML doc is the <SELECT> tag, your PHP script only needs to build the <OPTION> tags to go inside it, so you should remove lines 18-27 from your script, and replace with this:

while($row3 = sqlsrv_fetch_array($result)):
   printf('<option>%s</option>', $row3['Name']);
endwhile;

Open in new window

Give that a go, and if you're still struggling we may need to see a link to your page to figure things out.
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

Modified the code to this:

<?php
  error_reporting(E_ALL);
  ini_set("display_errors", 1);

  require_once('Connect_databse.php');
  $table1 = 'SHOW_UserOrganisation';

?>
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<title>Agrippa report system 2</title>
<link href="css/redmond/jquery-ui-1.8.13.custom.css" rel="stylesheet" />
</head>
<body>
<script type="text/javascript">

$(document).ready(function() {
$('#organisasjon').change(function() {
  $.ajax({
    url : 'selectbrukere.php',
    type : 'POST',
    data : { organisasjon : $(this).val() },
    success : function (data) {
      $("#brukere").html(data);
    }
  });
});

</script>


<table>
<!-- Start Organisasjon -->
  <tr>
  <td  class="rapport1_del3" align="right">Organisasjon:</td>
  <td align="left">
      <select id="organisasjon" name="organisasjon" class="selmenu" change="GetSubCategories()">
                  <?php

                     $query = "SELECT distinct(OrganisationName) FROM {$table1}";
//execute the SQL query and return records
                     $resultraptmp = sqlsrv_query( $conn,$query); 
// Parameter for rapport
                     while($row3 = sqlsrv_fetch_array($resultraptmp)){

                        $navnorganisasjon = $row3['OrganisationName'];
            
                        echo "<option ";
                        echo ">$navnorganisasjon</option>"; 
                  ?>
                   
    
<?php
}
?>    
    </select>
  </td>
  </tr>
<!-- END Organisasjon -->

<!-- Start Brukere -->
  <tr>
  <td  class="rapport1_del3" align="right">Bruker:</td>
  <td align="left">
      <select id="brukere" name="brukere" class="selmenu">
            
      </select>
  </td>
  </tr>
<!-- END Brukere -->

<!-- Start Brukere -->
 
<!-- END Brukere -->
</table>

</body>
</html>

Open in new window


******* selectbrukere.php *******

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

require_once('Connect_databse.php');

$table1 = 'SHOW_UserOrganisation';

$orgnavn = $_GET["organisasjon"];
// change the query so that the column names match your subcategory table
$query="select Name from {$table1} where OrganisationName=". $orgnavn;
$result = sqlsrv_query( $conn,$query); 
?>
<?php
while($row3 = sqlsrv_fetch_array($result)):
   printf('<option>%s</option>', $row3['Name']);
endwhile;

?>

Open in new window



But still dosent work ?

Here is the URL : http://agressiontestmysql.azurewebsites.net/mssql/test/test4.php
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
Comment Utility
OK.

Few things wrong, but we're getting there...

Firstly, you need to load the jQuery library in the HEAD of your document. Best to load this from Google. You're also missing a closing set of brackets in your Jquery (indentation helps out here)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Agrippa report system 2</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
     $('#organisasjon').change(function() {
          $.ajax({
               url : 'selectbrukere.php',
               type : 'POST',
               data : { organisasjon : $(this).val() },
               success : function (data) {
                    $("#brukere").html(data);
               }
          });
     });
});
</script>
</head>
<body>

Open in new window

Another problem is that when this function fires it returns a 404 error, meaning that selectbrukere.php can't be found. Because you've used a relative path for the AJAX call it's looking for it here:

http://agressiontestmysql.azurewebsites.net/mssql/test/selectbrukere.php

Finally, in your PHP script, you're still trying to grab the info from the GET array. You should be using the POST array:

$orgnavn = $_POST["organisasjon"];

Other than that, looking good :)
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

Still dosent work ?

<?php
  error_reporting(E_ALL);
  ini_set("display_errors", 1);

  require_once('Connect_databse.php');
  $table1 = 'SHOW_UserOrganisation';

?>
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<title>Agrippa report system 2</title>
<link href="css/redmond/jquery-ui-1.8.13.custom.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<script type="text/javascript">

$(document).ready(function() {
$('#organisasjon').change(function() {
  $.ajax({
    url : 'selektbrukere.php',
    type : 'POST',
    data : { organisasjon : $(this).val() },
    success : function (data) {
      $("#brukere").html(data);
    }
  });
});

</script>


<table>
<!-- Start Organisasjon -->
  <tr>
  <td  class="rapport1_del3" align="right">Organisasjon:</td>
  <td align="left">
      <select id="organisasjon" name="organisasjon" class="selmenu">
                  <?php

                     $query = "SELECT distinct(OrganisationName) FROM {$table1}";
//execute the SQL query and return records
                     $resultraptmp = sqlsrv_query( $conn,$query); 
// Parameter for rapport
                     while($row3 = sqlsrv_fetch_array($resultraptmp)){

                        $navnorganisasjon = $row3['OrganisationName'];
            
                        echo "<option ";
                        echo ">$navnorganisasjon</option>"; 
                  ?>
                   
    
<?php
}
?>    
    </select>
  </td>
  </tr>
<!-- END Organisasjon -->

<!-- Start Brukere -->
  <tr>
  <td  class="rapport1_del3" align="right">Bruker:</td>
  <td align="left">
      <select id="brukere" name="brukere" class="selmenu">
            
      </select>
  </td>
  </tr>
<!-- END Brukere -->

<!-- Start Brukere -->
 
<!-- END Brukere -->
</table>

</body>
</html>

Open in new window


******* selektbrukere.php *********

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

require_once('Connect_databse.php');

$table1 = 'SHOW_UserOrganisation';

$orgnavn = $_POST["organisasjon"];
// change the query so that the column names match your subcategory table
$query="select Name from {$table1} where OrganisationName=". $orgnavn;
$result = sqlsrv_query( $conn,$query); 
?>
<?php
while($row3 = sqlsrv_fetch_array($result)):
   printf('<option>%s</option>', $row3['Name']);
endwhile;

?>

Open in new window



Seems tahta selektbrukere.php is not called ?
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
It's important that you read the information I posted. I've already told you why it's not working.

You've fixed 2 of your problems, but left the other 2. Re-read my previous comment - you have a missing set of brackets at the end of your jQuery and even when that's fixed the file you are submitting your AJAX call to doesn't exist - you get a 404 File Not Found Error:

http://agressiontestmysql.azurewebsites.net/mssql/test/selectbrukere.php

Fix those 2 and it'll work fine.
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

Where some refresh isse here, have done the changes you say:

<script type="text/javascript">

$(document).ready(function() {
$('#organisasjon').change(function() {
  $.ajax({
    url : 'selektbrukere.php',
    type : 'POST',
    data : { organisasjon : $(this).val() },
    success : function (data) {
      $("#brukere").html(data);
    }
  });
});
})
</script>;

Open in new window



And testet this :

http://agressiontestmysql.azurewebsites.net/mssql/test/selektbrukere.php?organisasjon=Softkey

Then it shows:

Tor Erik Berg
Christian Svendesn


But why dosent it work when running;
http://agressiontestmysql.azurewebsites.net/mssql/test/test4.php

??
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Right. Now you've removed the jQuery library again so it won't work!!

Also, the fact that it works with the URL you've posted tells me that you have also reverted back to using the GET array instead of the POST array in your PHP script

It seems that you've removed the 2 fixes you did last time round (POST and jQuery), and fixed the 2 that you didn't (Brackets and 404) - why would you do that!!
0
 
LVL 2

Author Comment

by:team2005
Comment Utility
Hi!

I dont know what happend here, but it dident save my last changes...

Working perfect now :)

Thanks for BIG help here.

Is it possible to fill up a 3 listbox to, from same file -> selektbrukere.php ?
0
 
LVL 2

Author Closing Comment

by:team2005
Comment Utility
Thanks you for BIG help.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Is it possible to fill up a 3 listbox to, from same file -> selektbrukere.php
Yes. You would need your PHP script to create an array of the data, and then json_encode it to pass back to your jQuery. You set your AJAX request to retrieve JSON data and then you pull the 3 bits of info out of the response into the relevant SELECTs:

The PHP would look something like this (you'd create your dropdown options from your database):

<?php
$dropdown1 = <<<EOF
	<option>Value 1</option>
	<option>Value 2</option>
	<option>Value 3</option>
	<option>Value 4</option>
EOF;

$dropdown2 = <<<EOF
	<option>Value 5</option>
	<option>Value 6</option>
	<option>Value 7</option>
	<option>Value 8</option>
EOF;

$dropdown3 = <<<EOF
	<option>Value 9</option>
	<option>Value 10</option>
	<option>Value 11</option>
	<option>Value 12</option>
EOF;

$response = array(
	'text1' => $dropdown1,
	'text2' => $dropdown2,
	'text3' => $dropdown3,
);

echo json_encode($response);
?>

Open in new window

The jQuery would look something like this:

$('#organisasjon').change(function() {
	$.ajax({
		url : 'selektbrukere.php',
		type : 'POST',
		dataType: 'json',
		data : { organisasjon : $(this).val() },
		success : function (data) {
			$("#brukere").html(data.text1);
			$("#select2").html(data.text2);
			$("#select3").html(data.text3);
		}
	});
});

Open in new window

The text1, text2, text3 refer to the keys of your PHP array, and they will be put inside elements with IDs of brukere, select2, select3 respectively.

Glad you got it working :)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now