I have a dropdown named Category, the options are populated by a PHP script that queries for category names in a MySQL table.
Next to it, I have a dropdown named Subcategory, the options are also populated by a PHP script that queries for subcategory names in a MySQL table.
I'd like to re-run the subcategory query to change the values of the Subcategory dropdown, based on which category has been selected from the Category dropdown.
And I don't want the page to refresh, so I'm thinking jquery might have some use here?
Something like this?
$(document).ready(function(){
var select = $("#select-element");
select.change(function(){
$.ajax({
type : 'POST',
url: "url-of-your-php-script",
data: {
'data-name' : 'data-to-send'
}
success : function(returned){
// Append variable results to select..
}
});
});
});
The subcategory drop down should listen to the parent categories on change event. In Jquery you can do that using.
$('#parent').change(function(){
var parent = $(this).val();
// Remove current subcategory options
$('#child').children().remove();
// AJAX POST
$.ajax({
type:'POST',
data: 'parent='+parent,
url: 'process.php',
success: function(data){
// Fill the subcategory with new options using jquery each method
}
});
});
In general, you shouldn't use jQuery(or any other framework for that matter), unless you're already downloading it on a page. While your browser is downloading the scripts and libraries (of which, jQuery is probably going to be the largest), the rest of your page can't execute. I don't know why, but it won't download images, load iframes, nothing.
You can make an AJAX request to download the new content. Be careful, as this means you're essentially writing a webservice with access to your database, so make sure to validate inputs on both the server and in the javascript, as well as developing some kind of security for drop/delete actions.
Here's a native javascript tutorial for Ajax, but if you're hell bent on AJAX, you can use it.
The basic goal is this:
I implore you to be sure you understand AJAX in native code before you let jQuery do it all for you. Even if you choose to use the jQuery framework in the end, it will help you when debugging, upgrading, and reusing this code.