skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

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

  2. 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'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search