skip to Main Content

Problem:

I need to get the number 65 in strong tag.
I tried the following code, but it shows Uncaught ReferenceError.
(I’m a newbie and I spent for hours to create the following code but ended up like this…)
Would you please let me know how to fix this problem?

Code I tried:

<script type="text/javascript">
jQuery(document).ready(function ($) {
var getnum;
getnum = $('div.elementor-widget-container p > strong').text();
<?php $abc = "<script>document.write(getnum)</script>"?>   
});
</script>
<?php echo $abc;?>

Console error:

Uncaught ReferenceError: getnum is not defined

HTML (code came from a yith point & reward plugin):

<div class="elementor-element elementor-element-c1d0790 elementor-widget elementor-widget-text-editor" data-id="c1d0790" data-element_type="widget" id="pointsid" data-widget_type="text-editor.default">
    <div class="elementor-widget-container">
        <p>Your credit is  <strong>65</strong> Points</p>                       
    </div>
</div>

Thank you

2

Answers


  1. Getnum is defined when the document is loaded. When you access getnum, it is not yet declared.

    Login or Signup to reply.
  2. You’re mixing up javascript and php together. You could pass variables from server-side (i.e php) to client-side (i.e javascript) but not the other way around! At least not on the same page without using ajax. You could do it with ajax, but you’re not using ajax here. There are some tricks however, which are not recommended for the production.

    Also it’s worth mentioning that your question is not clear why you would want to do it like that.

    You would not get any error, if you write your code like this:

    <script type="text/javascript">
      jQuery(document).ready(function($) {
        let getnum = $('div.elementor-widget-container p > strong').text();
        console.log(getnum);
      });
    </script>
    

    Which will give you 65 in the console. However, you want to echo it out using php.

    The following "tricks" are NOT recommended for the production:

    • You could use "localStorage" in order to store your value and retrieve it again!
    • You could use "cookies" too!

    So your code would be something like this:

    <script type="text/javascript">
      jQuery(document).ready(function($) {
        let getnum = $('div.elementor-widget-container p > strong').text();
        localStorage.setItem("getnum", getnum);
      });
    </script>
    
    <?php echo "<script>document.write(localStorage.getItem('getnum'));</script>"; ?>
    

    Which will echo 65 onto the page using php!

    Let me know if that was what you were looking for!


    Tested and works fine!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search