I am trying to create a drop down list using jQuery, PHP and mySQL, here is my code thus far,
HTML:
<select id="box"></select><br />
<input id="button" type="button" value="populate" />
Javascript/jQuery:
$(document).ready(function() {
$("#button").click(function (){
$.getJSON("test_post.php", function(data){
$.each(data, function(user) {
$('#box').append(
$('<option></option>').html(user)
);
});
});
});
});
PHP:
mysql_connect('localhost', 'user', '1234');
mysql_select_db('json');
$test = mysql_query('SELECT user,pass FROM login WHERE user="john"');
while($row = mysql_fetch_array($test, true)) {
$data .= json_encode($row);
};
echo $data;
I have 3 entries in the database, and when I run the ‘test_post.php’ file, it echoes out the JSON, but when I try and get it to populate the drop down, nothing happens!
Any idea why?
There are several problems in your code.
First: attempt to use undefined variable
$data, you should have initialized it to an empty string beforewhileloop:$data = '';, otherwise this can send PHP notice with the JSON response, depending on values ofdisplay_errorsanderror_reportingsettings.Second: as @shamittomar said,
$datamust be an array andjson_encode()must be called only once for the whole array. For now, you’re sending several JSON objects concatenated to a single string, which is wrong.Third: value of the
userfunction parameter in the JavaScript is actually an index of thedataarray, not a value, but even ifuserwould be a value, it would be a JavaScript object withuserandpassproperties, not a string.Resulting code should be (changed parts only):
PHP
JavaScript