I am just trying to select parent box then want to have child according to the parent, my aim is to create Parent(Country) and Child(City) Selectbox, when someone select country then it should show cities of that country which are stored in DB. The page should not reload when user select country but it should hit the DB and fetch cities of that Country, I created a Wordpress page and having the long from there here i am just putting the parent and child selectbox of my html.
HTML Page/Wordpress Page:
<select name="PER_COUNTRY" id="PER_COUNTRY">
<?php $rows= $wpdb->get_results($wpdb->prepare("SELECT * FROM country ORDER BY countryname" ,13,'gargle'),ARRAY_A);
foreach($rows as $row){?>
<option value="<?php echo $row["countrycode"]?>"><?php echo $row["countryname"]?></option>
</select>
Plugin folder is created with same name ajax-test, and placed 2 files there 1 is ajax-test.php and test.js
code of ajax-test.php is below:
<?php
/**
* Plugin Name: Ajax Test
* Plugin URI: http://test.org
* Description: Allows users to select cities
* Version: 1.0.0
* Author: Javed
* Author URI: http://test.org
* License: GPL2
*/
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/test.js', __FILE__ ), array('jquery'));
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )));
}
function my_action() {
$country_id = $_REQUEST['country_id'];
echo $country_id;
die();
}
add_action('wp_ajax_my_action', 'my_action' );
add_action('wp_ajax_nopriv_my_action', 'my_action');
?>
in the above code i didn't call global db if i can process value of user selected box here and can send back to the child selectbox, then i can do DB and table query myself.
and test.js file code is:
jQuery(document).ready(function(){
jQuery('#PER_COUNTRY').change(function(){
var country_id = jQuery(this).val();
// alert(country_id);
jQuery.ajax
({
type: 'post',
url: ajax_object.ajax_url,
data: {
action : 'my_action',
country_id : country_id,
},
success: function(data)
{
alert(data);
}
});
});
});
As you can see that // alert(country_id); is commented in test.js this is for test, yes it is getting value but i think problem is with Ajax post, need your help in this regard, kindly guide me. What is wrong i'm doing here, i have already read so many tutorials but i didn't find any mistake in my code.