The mystery of '$.md5 is not a function'

Viewed 3332

I have a js code that uses jQuery.MD5 library. It works perfectly on my server:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://example.com/static/js/jquery.md5.js"></script>
</head>
<body>
    <script>
      // my code goes here (declaring variables and functions)
      var code = $.md5('mystring');
      // and a little more code
    </script>
</body>

But then I upload it to a web application (which I cannot control), that makes it look like this and puts it into an iframe:

<head>
  <script>
    // some extra variables are declared here
    // double-checked that nothing here can break my code
  </script>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://example.com/static/js/jquery.md5.js"></script>
    <script>
        // some code
        var code = $.md5('mystring');
        // some code
    </script>
</body>

And this code starts giving me the $.md5 is not a function error. Strange thing. Tried clearing the cache, putting jquery.md5.js code directly into mine, nothing works.

Note that all the code works on my machine, so there must be no problem with my JS.

Update: the problematic code behavior seems to be unpredictable, meaning that sometimes it works fine with no changes.

What can be wrong?

2 Answers

If you want to use jQuery md5 function you should have import jquery.md5.js file in your project.

Steps-

  1. Download jquery.md5.js file from https://github.com/placemarker/jQuery-MD5

  2. Copy this file into your source folder. (ex: assert/theme/js)

  3. Import that js file to your project. (ex: <script src="<?= base_url(); ?>/public/assert/theme/js/jquery.md5.js"></script>

)

That's it! You are done!

Related