I have an html page that would send json request to get the data from a server [though php-mysql]. I see that the response is not being received. I tried debugging through fiddler and could see that “The response does not contain valid json text.
My code is below
html
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript">
</script>
<script type="text/javascript">
function populateFruitVariety() {
$.getJSON('serverside.php',
{fruitName:$('#fruitName').val()},
function(data) {
var select = $('#fruitVariety');
if(select.prop) {
var options = select.attr('options');
} else {
var options = select.attr('options');
}
$('option', select).remove();
$.each(data, function(val, text) {
options[options.length] = new Option(text, val);
});
});
}
$(document).ready(function() {
populateFruitVariety();
$('#fruitName').change(function() {
populateFruitVariety();
});
});
</script>
<form>
Fruit:
<select name="name" id="fruitName">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Pear</option>
</select>
Variety:
<select name="variety" id="fruitVariety">
</select>
</form>
</html>
serverside.php
<?php
header('Content-type: application/json');
$host="localhost";
$username="root";
$password="";
$database="db_common";
$table_fruit_info = "fruit_info";
$tc_fruit_id = "fruit_id";
$tc_fruit_index = 'fruit_index';
$con = mysql_connect("$host", "$username", "$password")
or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
if(isset($_GET['fruitName'])) {
$fruit_id = $_GET['fruitName'];
$result = mysql_query("SELECT * FROM $table_fruit_info
WHERE $tc_fruit_id='$fruit_id'");
while($rows = mysql_fetch_array($result))
{
$ret_fruitIndex = $rows[$tc_fruit_index];
}
}
echo json_encode($ret_fruitIndex);
?>
Thanks for your help!
It looks like
$ret_fruitIndexis just a string, which dosn’t have an appropirate JSON representative. In your while loop, you are overwriting the value for this variable with each pass, which I assume is not what you are wanting to do.I assume you really want to so something like:
As an side you code is very vulnerable to SQL injection and you also should not be using teh
mysql_*functions which are deprecated. I would suggest usingmysqli_*functions, PDO, or something more modern and secure.With regards to your jQuery: I am not sure what you are doing here:
As there is not any difference in cases there.
I also believe your
each()function is wrong. The parameters passed to the callback function will be the index value of data and the value for that index.You logic should be to remove all options, than add new options based on data, so I don;t know why the
optionsvariable has any involvement in this callback function at all.