Mark Mark - 23 days ago 8
Ajax Question

Ajax load wordpress template part

I have 2 radio buttons in a form for payment method - I want to load a template part on click via ajax.

Right now I can load only the credit card form - what i'm trying to do is if credit card is selected then load credit card template if paypal is selected then load paypal template part.

Form Elements

<input type="radio" class="radio-cc" name="method" value="creditcard"><span class="radio-span">Credit Card</span>
<input type="radio" class="radio-paypal" name="method" value="paypal"><span class="radio-span">Paypal</span>


jQuery

$("input[name=method]").change(function(){
$.ajax({
type: 'GET',
url: '<?php echo admin_url('admin-ajax.php');?>',
data: {
action: 'CCAjax'
},
success: function(textStatus){
$( '.default-form' ).append( textStatus );
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});


PHP

function CCAjax()
{
get_template_part('cc');
die();
}

// creating Ajax call for WordPress
add_action('wp_ajax_nopriv_CCAjax', 'CCAjax');
add_action('wp_ajax_CCAjax', 'CCAjax');

Answer Source

You have to pass the Value of the chosen method:

jQuery

$("input[name=method]").change(function(){
  var chosenmethod = $(this).val();
  $.ajax({  
    type: 'GET',  
    url: '<?php echo admin_url('admin-ajax.php');?>',  
    data: { action : 'CCAjax', chosen : chosenmethod },  
    success: function(textStatus){  
       $( '.default-form' ).html( textStatus ); 
    },  
    error: function(MLHttpRequest, textStatus, errorThrown){  
        alert(errorThrown);  
    }  
  });  
});

PHP

function CCAjax()
{
   if($_POST['chosen']=='creditcard'){
     get_template_part('cc');
   } else {
     get_template_part('paypal');
   }
   exit();
}

// creating Ajax call for WordPress  
add_action('wp_ajax_nopriv_CCAjax', 'CCAjax');
add_action('wp_ajax_CCAjax', 'CCAjax');