开发者

values of one combo box on basis of other combo box - php

开发者 https://www.devze.com 2023-02-06 20:04 出处:网络
i have two tables categories and sub-categories in database. On my form i have two combo boxes category and sub categories. Now i want that when i change category, subcategories should change accordin

i have two tables categories and sub-categories in database. On my form i have two combo boxes category and sub categories. Now i want that when i change category, subcategories should change accordingly. I can do it if arrays are defined in javascript. but in my case subcategories are to load from database on the basis of value of category selected. i can fetch data from database using php. if data is in 开发者_高级运维php array how will i pass it to javascript. how can i solve this problem without ajax? if the solution is JSON then how can i implement json as i never used it.


The PHP code is server-side and it's evaluated first, client-side code (like Javascript) is processed after. So you'd have to pre-fetch all the data you need to switch between through PHP so you can manipulate them via javascript.

EDIT:

example:

<?php

   $arej[]="one";
   $arej[]="two";
   $arej[]="three";
   $arej[]="four";
?>
<script type="javascript">

var jarray = new Array;

<?php
for($i=0;$i<count($arej); $i++){
   echo "jarray[$i]='".$arej[$i]."';";
} 
?>

</script>


Either you put all your subcategories in your JavaScript or you'll have to use Ajax.

It's very easy to pass data from PHP to JavaScript. If you have your subcategories in the array $subcategories you can use the result of json_encode($subcategories) safely in your JavaScript (it - o wonder - JSON encodes your array).

So either you make an Ajax service which returns a specific subcategory or you write a PHP script which generates a JavaScript array containing all subcategories.

A simple Ajax service could look like this:

$id = (int)$_GET['category']; // The id of the category
$subcategories = ... // Fetch array of subcategories from db
echo json_encode($subcategories);

So everytime the user click on another category, your JavaScript has to make an Ajax call to the script above, specifying the new category id.

If you use jQuery, doing Ajax is very easy.

$.ajax({
  url: "subcategories.php?cat=123",
  success: function(encoded){
    $("#output").append(encoded);
  }
});

(The example above more or less comes directly from the jQuery docs.) To parse JSON in JavaScript you could use eval(), but that function is evil. Better use JSON.parse() or the jQuery alternative.

var subcategories = JSON.parse(encoded);

Now the variable subcategories contains exact the same datastructure as your $subcategories in the PHP script contained.

0

精彩评论

暂无评论...
验证码 换一张
取 消