1

I'm using wordpress ajax to capture value of a radio input when click. All I want is to echo the result into >>>php<<< as a variable on the theme.

i've tried to do a global variable, but i know nothing about it. And call it into the theme, not working.

wp theme

<input class="inputsin" type="radio" name="deporte" value="<?php echo $deporte ?>">

<?php $deporte_name = 'RESULT I WANT TO PRINT HERE'; ?>

<div class="result">NOT HERE</div>

conjx.js

(function($){

    $('input[type=radio]').on('click',function(){

        /CAMPOS DE SELECCION/
        var deport = $('input:radio[name=Deporte]:checked').val();
        console.log(deport);


        $.ajax({
            url :dcms_vars.ajaxurl,
            type : 'post',
            data : {
                action:'dcms_ajax_readmore',
                Deporte:deport
            },
            success: function(datos) {
                $('.result').html(datos);
                }
           });
    });
})(jQuery);

functions.php

add_action('wp_enqueue_scripts', 'dcms_insertar_js');

function dcms_insertar_js(){

    wp_register_script('dcms_miscript', get_template_directory_uri(). '/js/conjx.js', array('jquery'),'1',true );
    wp_enqueue_script('dcms_miscript');

    wp_localize_script('dcms_miscript','dcms_vars',['ajaxurl'=>admin_url('admin-ajax.php')]);
}
add_action('wp_ajax_nopriv_dcms_ajax_readmore','dcms_enviar_contenido');
add_action('wp_ajax_dcms_ajax_readmore','dcms_enviar_contenido');

function dcms_enviar_contenido()
{
    $deportphp = $_POST['Deporte'];
       echo $deportphp;
    wp_die();
}

1 Answer 1

0

I believe you may have a misunderstanding of AJAX. When an AJAX call is made, it will create a separate thread which sends data to the URL stated. In the case of WordPress, it will call the wp ajax file, which will direct to your function.

This function will run independent from anything else running on your site, and the echo will be sent back to your AJAX call as a return, and then that thread will die. Since PHP is run server side and JS is run client side, you can not assign PHP variables from JS (Since the server side would finish running before the client side loads).

If all you want to do is insert the radio button value into different places within the DOM, you can do so using jQuery without an AJAX call.

Sign up to request clarification or add additional context in comments.

1 Comment

Understood, my only question is how to print my radio's value into a php variable when it's checked. Cause i can only print plain text into my html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.