JSON com jQuery, PHP e MySQL

Bem, navegando pela net achei um tutorial legal sobre JSON com jQuery, PHP e MySQL.

E resolvi postar…

Este post mostra como preencher uma caixa de seleção com base no valor de outra, pela obtenção de dados JSON com jQuery a partir de um script PHP que obtém os dados de um banco de dados MySQL.

Código HTML

O código em HTML inicial é assim:

[code language=”html”]
<pre>
<div><form></div>
Frutas:</div>
<select name=”name” id=”fruitName”>
<option>Maçã</option>
<option>Laranja</option
<option>Banana</option>
<option>Pera</option>
</select>
</form>
Veriedades:
<select name=”variety” id=”fruitVariety”>
</select>
[/code]

O conjunto de nomes de frutas já está habitado no lado do servidor e o conjunto padrão de variedades pode ser muito, para preenchê-los com Javascript siga este tutorial.

Código jQuery

O código jQuery precisa inicialmente preencher o select das variedades com base no valor do select de frutos. Em seguida, ele necessita de atualizar as variedades o select de fruta mudar.
Supondo que o script PHP para pegar a fruta está em “/variedades.php” faça isso:

[code language=”jquery”]
function popularfrutas() {
$.getJSON(‘/variedades.php’, {fruitName:$(‘#fruitName’).val()}, function(data) {
var select = $(‘#fruitVariety’);
var options = select.attr(‘options’);
options[options.length] =
$(‘option’, select).remove();</div>
$.each(data, function(index, array) {
new Option(array[‘variety’]);
});
});

}

$(document).ready(function() {

<pre>
<pre>
<pre>popularfrutas</pre>
</pre>
</pre>
();
$(‘#fruitName’).change(function() {
populateFruitVariety();
});

});</pre>
</pre>
[/code]

Assuming the PHP script to fetch the fruit is at /fruit-varieties.php do this:
function populateFruitVariety() {
$.getJSON(‘/fruit-varities.php’, {fruitName:$(‘#fruitName’).val()}, function(data) {
var select = $(‘#fruitVariety’);
var options = select.attr(‘options’);
options[options.length] =
$(‘option’, select).remove();
$.each(data, function(index, array) {
 new Option(array['variety']);
        });
populat
});

}

$(document).ready(function() {

 eFruitVariety();
 $('#fruitName').change(function() {
  populateFruitVariety();
 });

});
The “$.getJSON(‘/fruit-varities.php’, {fruitName:$(‘#fruitName’).val()}” line is what retrieves the data and it passes the currently selected fruit name value as part of the get string to the PHP script.

PHP Code

The PHP script connects to the database, retrieves the data for the selected fruit name and then returns it as a JSON encoded string.
$dsn = “mysql:host=localhost;dbname=[DATABASE NAME HERE]”;
$username = “[USERNAME HERE]”;
$pdo = new PDO($dsn, $usernam
$password = “[PASSWORD HERE]”;
e, $password);
{     $stmt = $p
$rows = array();
if(isset($_GET['fruitName']))
do->prepare(“SELECT variety FROM fruit WHERE name = ? ORDER BY variety”);
$stmt->execute(array($_GET['fruitName']));
} echo json_encode($rows);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Caching issues

Internet Explorer and Firefox will cache the subsequent requests made to the same fruit name but the other browsers won’t, requesting them again each time.

Further reading

I haven’t written much in the way of comments for each of the above code snippets; they’ve all been covered to some degree in previous posts which led up to this one. Please refer to these in the  “Related Posts” list below.

Deixe um comentário

O seu endereço de e-mail não será publicado.