Morts81
Morts81

Reputation: 439

Sending HTML Radio Button Selection Through AJAX

I'll start this by saying I've delved through copious amounts of other posts to try and find the solution however I've not been able get my code to work.

What I'm trying to do is send a variable from a radio button selection through AJAX to PHP. I don't want to have to add a submit button, I want the PHP code to process once a radio button is toggled.

My simple code is as follows, similar on.change code I've successfully used for dropdown menus but I'm struggling to get the same functionality for radio buttons.

Appreciate any assistance available.

HTML RADIO BUTTONS

<form>
<div class="label"><b>Include Points?</b></div>
<input type="radio" name="Pts" value="On" /> On
<input type="radio" name="Pts" value="Off" checked="checked" /> Off
</form> 

JQUERY AJAX

jQuery(document).ready( function($) {
    jQuery('#Pts').on( 'click', function () {
         Pts = $('input:radio[name=Pts]:checked').val();
     jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'call_radio_practice',
            Pts: Pts,
        },
         success:function(output){
             jQuery('#practice').html( output );
         }
     });
    }).click();
});

PHP

$Pts = $_POST['Pts'];
print_r($Pts);

Upvotes: 0

Views: 43

Answers (1)

Đ&#224;o Minh Hạt
Đ&#224;o Minh Hạt

Reputation: 2930

You don't have this selector jQuery('#Pts') (id Pts).

Change to listen to change event on input:radio[name=Pts]

jQuery(document).ready( function($) {
    jQuery('input:radio[name=Pts]').on('change', function () {
         Pts = $('input:radio[name=Pts]:checked').val();
     jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'call_radio_practice',
            Pts: Pts,
        },
         success:function(output){
             jQuery('#practice').html( output );
         }
     });
    });
});

Upvotes: 1

Related Questions