Solved

jQuery fill selectbox from database

Posted on 2010-08-15
17
689 Views
Last Modified: 2012-05-10
Hey guys,

well I'm having some problems with the following code.
I'm trying to fill a selectbox with data from the database.
I've got this so far
	$("input#artistname").change(function() { 
		UpdateDropDown($(this).val());
    });

    function UpdateDropDown(artist) {
		
		jQuery.post('get-albums.php', 
		{parameterSentToServer1:'value', param2:'value2'}, 
		function(data){jQuery('select#select_albumname option').remove(); //Remove current options
		
		for (var option in data.results){
			jQuery('select#select_albumname').append('<option value="'+option.value+'">'+option.name+'</option>');
		}}, 'json');
    }

Open in new window


In the .php file I've given a static result
echo '{results:[{value:1, name:"album1"}]}';

So I think it should work, but it's not working. What am I doin wrong here?
0
Comment
Question by:Serellyn
  • 10
  • 7
17 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 33442254
Not sure you return value and name keys+values from your php function :

value and name

{"results":[{"value":"","name":"Choose one"},{"value":"1","name":"Exodus"},{"value":"2","name":"Uprising"}]}

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442255
Try this for testing purpose :


<?PHP
	echo json_encode(array(results=>array(array(value=>"",name=>"Choose one"), array(value=>"1",name=>"Exodus"), array(value=>"2",name=>"Uprising"))));
?>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442272
If it don't work, check this working code with the previous php code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="javascript">
	$(document).ready(function() {
		$("#getalbum").click(function() {
			UpdateDropDown( $("#artist").val() );
		});
	});
	function UpdateDropDown(artist) {
		jQuery.post('get-albums.php',
			{ "parameterSentToServer1":"value", "param2":"value2" },
			function(data) {
				jQuery('select#select_albumname option').remove();
				jQuery.map(data.results, function(option) {
					jQuery('select#select_albumname').append('<option value="'+option.value+'">'+option.name+'</option>');
				})
			},
			'json'
		);
	}
</script>
</head>
<body>
<input id="artist" type="text" readonly="readonly" value="Bob Marley" /><input id="getalbum"  type="button" value="get Albums" /><br />
<select id="select_albumname"><option value="test">test</option></select>
</body>
</html>

Open in new window

0
 
LVL 1

Author Comment

by:Serellyn
ID: 33442274
Hello Leakim,

with your second snippit the selectbox gets filled, but it fills up with UNDEFINED (4 times)
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442285
which one ? #33442272 ?
0
 
LVL 1

Author Comment

by:Serellyn
ID: 33442292
No, 33442255, it returns UNDEFINED (4 times) in the selectbox.
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 33442306
OK, use the call function
function(data) {
				jQuery('select#select_albumname option').remove();
				jQuery.map(data.results, function(option) {
					jQuery('select#select_albumname').append('<option value="'+option.value+'">'+option.name+'</option>');
				})
			}

Open in new window

0
 
LVL 1

Author Closing Comment

by:Serellyn
ID: 33442314
And now it works like a charm, thank you
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 82

Expert Comment

by:leakim971
ID: 33442322
You're welcome! Thanks for the points!
0
 
LVL 1

Author Comment

by:Serellyn
ID: 33442412
Hey leakim, just one more question, you might know and I really need it.
I now need to get values from the databse.
So I've got this

// QUERY IS HERE

$j = array();
while ($row = mysql_fetch_array($get_albums_sql))
{
       //array needs to be created here
}

So how can I now create that array that you've created staticly for me?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442435
something like :


$j = array();
while ($row = mysql_fetch_array($get_albums_sql)) 
{
      $j[] = array(value=>$row[0],name=>$row[1]);
}
echo json_encode(array("results"=>$j));

Open in new window

0
 
LVL 1

Author Comment

by:Serellyn
ID: 33442439
You sir, are a genius!
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442450
;-)
0
 
LVL 1

Author Comment

by:Serellyn
ID: 33442465
Something stupid though, first I did this, and it did select everything from nightwish.
$artistname = 'nightwish';

Now I'm doing $artistname = trim($_POST['artistname']);
And when I now enter nightwish, nothing happens...
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442493
from your code you send : { "parameterSentToServer1":"value", "param2":"value2" },

no artistname
0
 
LVL 1

Author Comment

by:Serellyn
ID: 33442531
I'd figure you would like some points, you deserve them since you've helped me again.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_26404631.html
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33442543
^_^ I 'm going to check your account twice now! Thanks
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

914 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

14 Experts available now in Live!

Get 1:1 Help Now