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.
i have two tables categories and sub-categories in database. On my form i have
Share
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
$subcategoriesyou can use the result ofjson_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:
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.
(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 useJSON.parse()or the jQuery alternative.Now the variable
subcategoriescontains exact the same datastructure as your$subcategoriesin the PHP script contained.