Home > Net >  Function doesn't echo variable
Function doesn't echo variable

Time:12-26

I'm currently learning basic php and jQuery.

I've created script which is getting url on mouse hover, and sends it to php.

The problem is, if I want to pass this data to php variable, it seems like it doesn't work because it echos only "'This is our JS Variable :'"

Script:

<script type="text/javascript">
    
var hrefValue;

jQuery(document).ready(function($) {
    $('#bio-box').find('a').mouseover(function() {
        hrefValue = ($(this).attr('href'))
       console.log(hrefValue)
    });
    $.ajax({
        url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
        data: {
            'action': 'php_tutorial',
            'php_test': hrefValue
        },
        success: function(data){
            console.log("happy")
        }
    });
}); 

</script>

functions.php:

function our_tutorial(){
        if(isset($_REQUEST)){
            $testing = $_REQUEST['php_test'];
    
            echo 'This is our JS Variable :'.$testing;
    
            global $wpdb;
            $wpdb->insert(
                $wpdb->prefix.'lms_enroll',
                [
                    'ID' => $testing
                ]
            );
        }
        die();
    }
    add_action('wp_ajax_php_tutorial', 'our_tutorial');

CodePudding user response:

Solution:

  $.ajax({
        url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
        type: 'post', // define type
        data: {
            'action': 'php_tutorial',
            'php_test': hrefValue
        },
        success: function(data){
            console.log("happy")
        }
    });


functions.php:
// post to et value
$test = $_POST['php_test'];

CodePudding user response:

The problem was when page loaded, value of a variable was empty. The solution was to call ajax in the moment of mouseover

  • Related