Thursday, January 6, 2022

[FIXED] Function doesn't echo variable

Issue

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');

Solution

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

 var hrefValue;

jQuery(document).ready(function($) {
    $('#bio-box').find('a').mouseover(function() {
        hrefValue = ($(this).attr('href'))
        //console.log(hrefValue)
        $.ajax({
            url: frontendajax.ajaxurl,
            type: 'POST', 
            data: {
                'action': 'image',
                'php_test': hrefValue
            },
            success: function(data){
                $('#featured-image').html(data);
                //console.log(data);
            }
        });
    });
}); 


Answered By - trz

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.