PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 6, 2022

[FIXED] Function doesn't echo variable

 January 06, 2022     ajax, echo, php, wordpress     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing