{"id":4420,"date":"2011-01-11T07:52:01","date_gmt":"2011-01-11T07:52:01","guid":{"rendered":"http:\/\/www.softov.com.br\/blog\/?p=134"},"modified":"2019-02-02T01:43:20","modified_gmt":"2019-02-02T01:43:20","slug":"json-com-jquery-php-e-mysql","status":"publish","type":"post","link":"https:\/\/softov.com.br\/blog\/2011\/01\/11\/json-com-jquery-php-e-mysql\/","title":{"rendered":"JSON com jQuery, PHP e MySQL"},"content":{"rendered":"<p>Bem, navegando pela net achei um tutorial legal sobre JSON com jQuery, PHP e MySQL.<\/p>\n<p>E resolvi postar&#8230;<\/p>\n<p>Este post mostra como preencher uma caixa de sele\u00e7\u00e3o com base no valor de outra, pela obten\u00e7\u00e3o de dados JSON com jQuery a partir de um script PHP que obt\u00e9m os dados de um banco de dados MySQL.<\/p>\n<h3>C\u00f3digo HTML<\/h3>\n<p>O c\u00f3digo em HTML inicial \u00e9 assim:<\/p>\n<p>[code language=&#8221;html&#8221;]<br \/>\n&lt;pre&gt;<br \/>\n&lt;div&gt;&lt;form&gt;&lt;\/div&gt;<br \/>\nFrutas:&lt;\/div&gt;<br \/>\n&lt;select name=&#8221;name&#8221; id=&#8221;fruitName&#8221;&gt;<br \/>\n&lt;option&gt;Ma\u00e7\u00e3&lt;\/option&gt;<br \/>\n&lt;option&gt;Laranja&lt;\/option<br \/>\n&lt;option&gt;Banana&lt;\/option&gt;<br \/>\n&lt;option&gt;Pera&lt;\/option&gt;<br \/>\n&lt;\/select&gt;<br \/>\n&lt;\/form&gt;<br \/>\nVeriedades:<br \/>\n&lt;select name=&#8221;variety&#8221; id=&#8221;fruitVariety&#8221;&gt;<br \/>\n&lt;\/select&gt;<br \/>\n[\/code]<\/p>\n<p>O conjunto de nomes de frutas j\u00e1 est\u00e1 habitado no lado do servidor e o conjunto padr\u00e3o de variedades pode ser muito, para preench\u00ea-los com Javascript siga este tutorial.<\/p>\n<h3>C\u00f3digo jQuery<\/h3>\n<p>O c\u00f3digo 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.<br \/>\nSupondo que o script PHP para pegar a fruta est\u00e1 em &#8220;\/variedades.php&#8221; fa\u00e7a isso:<\/p>\n<p>[code language=&#8221;jquery&#8221;]<br \/>\nfunction popularfrutas() {<br \/>\n$.getJSON(&#8216;\/variedades.php&#8217;, {fruitName:$(&#8216;#fruitName&#8217;).val()}, function(data) {<br \/>\nvar select = $(&#8216;#fruitVariety&#8217;);<br \/>\nvar options = select.attr(&#8216;options&#8217;);<br \/>\noptions[options.length] =<br \/>\n$(&#8216;option&#8217;, select).remove();&lt;\/div&gt;<br \/>\n$.each(data, function(index, array) {<br \/>\nnew Option(array[&#8216;variety&#8217;]);<br \/>\n});<br \/>\n});<\/p>\n<p>}<\/p>\n<p>$(document).ready(function() {<\/p>\n<p>&lt;pre&gt;<br \/>\n&lt;pre&gt;<br \/>\n&lt;pre&gt;popularfrutas&lt;\/pre&gt;<br \/>\n&lt;\/pre&gt;<br \/>\n&lt;\/pre&gt;<br \/>\n();<br \/>\n$(&#8216;#fruitName&#8217;).change(function() {<br \/>\npopulateFruitVariety();<br \/>\n});<\/p>\n<p>});&lt;\/pre&gt;<br \/>\n&lt;\/pre&gt;<br \/>\n[\/code]<\/p>\n<div>Assuming the PHP script to fetch the fruit is at \/fruit-varieties.php do this:<\/div>\n<div>function populateFruitVariety() {<\/div>\n<div>$.getJSON(&#8216;\/fruit-varities.php&#8217;, {fruitName:$(&#8216;#fruitName&#8217;).val()}, function(data) {<\/div>\n<div>var select = $(&#8216;#fruitVariety&#8217;);<\/div>\n<div>var options = select.attr(&#8216;options&#8217;);<\/div>\n<div>options[options.length] =<\/div>\n<div>$(&#8216;option&#8217;, select).remove();<\/div>\n<div>$.each(data, function(index, array) {<\/div>\n<pre>\r\n new Option(array['variety']);\r\n        });<\/pre>\n<div>populat<\/div>\n<pre>\r\n});\r\n\r\n}\r\n\r\n$(document).ready(function() {\r\n\r\n eFruitVariety();\r\n $('#fruitName').change(function() {\r\n  populateFruitVariety();\r\n });\r\n\r\n});<\/pre>\n<div>The &#8220;$.getJSON(&#8216;\/fruit-varities.php&#8217;, {fruitName:$(&#8216;#fruitName&#8217;).val()}&#8221; 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.<\/div>\n<h2>PHP Code<\/h2>\n<div>The PHP script connects to the database, retrieves the data for the selected fruit name and then returns it as a JSON encoded string.<\/div>\n<div>$dsn = &#8220;mysql:host=localhost;dbname=[DATABASE NAME HERE]&#8221;;<\/div>\n<div>$username = &#8220;[USERNAME HERE]&#8221;;<\/div>\n<div>$pdo = new PDO($dsn, $usernam<\/div>\n<div>$password = &#8220;[PASSWORD HERE]&#8221;;<\/div>\n<pre>\r\ne, $password);<\/pre>\n<div>{ \u00a0\u00a0\u00a0 $stmt = $p<\/div>\n<pre>\r\n$rows = array();\r\nif(isset($_GET['fruitName']))<\/pre>\n<div>do-&gt;prepare(&#8220;SELECT variety FROM fruit WHERE name = ? ORDER BY variety&#8221;);<\/div>\n<pre>\r\n$stmt-&gt;execute(array($_GET['fruitName']));<\/pre>\n<div>} echo json_encode($rows);<\/div>\n<div>\u00a0\u00a0\u00a0 $rows = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);<\/div>\n<h2>Caching issues<\/h2>\n<div>Internet Explorer and Firefox will cache the subsequent requests made to the same fruit name but the other browsers won&#8217;t, requesting them again each time.<\/div>\n<h2>Further reading<\/h2>\n<div>I haven&#8217;t written much in the way of comments for each of the above code snippets; they&#8217;ve all been covered to some degree in previous posts which led up to this one. Please refer to these in the \u00a0&#8220;Related Posts&#8221; list below.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Bem, navegando pela net achei um tutorial legal sobre JSON com jQuery, PHP e MySQL. E resolvi postar&#8230; Este post mostra como preencher uma caixa de sele\u00e7\u00e3o com base no valor de outra, pela obten\u00e7\u00e3o de dados JSON com jQuery a partir de um script PHP que obt\u00e9m os dados de um banco de dados&hellip; <a class=\"more-link\" href=\"https:\/\/softov.com.br\/blog\/2011\/01\/11\/json-com-jquery-php-e-mysql\/\">Continuar lendo <span class=\"screen-reader-text\">JSON com jQuery, PHP e MySQL<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[24],"tags":[103,59,105,106],"_links":{"self":[{"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/posts\/4420"}],"collection":[{"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/comments?post=4420"}],"version-history":[{"count":1,"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/posts\/4420\/revisions"}],"predecessor-version":[{"id":4581,"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/posts\/4420\/revisions\/4581"}],"wp:attachment":[{"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/media?parent=4420"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/categories?post=4420"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/softov.com.br\/blog\/wp-json\/wp\/v2\/tags?post=4420"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}