This question already has an answer here:
I have two radio buttons in a wordpress file. I have two contact-form-7 shortcodes and want to execute one if the radio is clicked "Yes" and the other if the radio button is "No". I am willing to use ajax as i don't want the page to reload but have no idea how to use it. It will be great if you could guide me.
Example HTML:
<input type=radio name=radio value=yes/>
<input type=radio name=radio value=no/>
<script>
if(radio==yes){
call_php_shortcode1();
}elseid(radio == no){
call_php_shortcode2();
}
</script>
</div>
Call the function on click radio button first:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
Then inside the function you can call ajax,
function myFunction(){
$.ajax(this.href, {
success: function(data) {
$('#main').html($(data).find('#main *'));
$('#notification-bar').text('The page has been successfully loaded');
},
error: function() {
$('#notification-bar').text('An error occurred');
}
});
}
You can direct call the ajax also inside the radio button is checked condition.
Hope this will help you.
Thanks.
Please go through the following steps.
Step-1: Copy and Paste the below radion buttons code in your php file.
<input type="radio" name="radio" value="yes" onclick="getRadioVaal(this.value)"/>Form1
<input type="radio" name="radio" value="no" onclick="getRadioVaal(this.value)"/> Form2
<div id="result"></div>
Step-2: Copy and Paste the below javascript code in same php file.
<script type="text/javascript">
function getRadioVaal(radio_val){
// alert(radio_val);
$.ajax({
type: "POST",
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: "action=get_radio_button_vale&radio_val="+radio_val,
success:function(response){
$('#result').html(response);
}
});
}
</script>
Step-2: Copy and Paste the below code snipeet in your theme functions.php file.
//Ajax call for display form on click radio button
function display_contact_form(){
if($_POST['radio_val'] === 'yes'){
echo do_shortcode('[contact-form-7 id="28" title="Contact form 1"]');
}else if($_POST['radio_val'] === 'no'){
echo do_shortcode('[contact-form-7 id="29" title="Contact form 2"]');
}
exit;
}
add_action( 'wp_ajax_get_radio_button_vale', 'display_contact_form' );
add_action( 'wp_ajax_nopriv_get_radio_button_vale', 'display_contact_form' );