0

I am building a Grid with some values on the backend using PHP and then I am sending it through JSON using and AJAX call to the view. One of these values is an image wrapped in a a element with a Javascript function call. For example:

<a class="actionimage" target="_blank" href='javascript:addException(0,"name");void(0);'>
    <img src="/images/icons/16x16/delete.png">
</a>

The function addException() already exists on the page before the AJAX call so when I try to execute the function on the newest elements added to the DOM it (the function) doesn't work because doesn't know about them.

Let me explain what's is above better:

  • I call the URL
  • Page gets render
  • The result is something like meaning the function addException() is rendered when page loads for first time. Notice that I didn't add anything related to the grid.

    <div class="grid" id="grid></div>
    <script>
        $(function(){
            function addException(param1, param2) {
                // ....
            }
        });
    </script>
    ...
    
  • An AJAX call is made ....
  • The following block is built dynamically using the AJAX results:

    <div class="grid" id="grid">
        <a class="actionimage" target="_blank" href='javascript:addException(0,"name");void(0);'>
            <img src="/images/icons/16x16/delete.png">
        </a>
    

  • The final result would be something like:

    <div class="grid" id="grid">
        <a class="actionimage" target="_blank" href='javascript:addException(0,"name");void(0);'>
            <img src="/images/icons/16x16/delete.png">
        </a>
    </div>
    
    <script>
        $(function(){
            function addException(param1, param2) {
                // ....
            }
        });
    </script>
    

Having that you can click on the image and you'll see how the function is not called because it doesn't know about the new elements added to the DOM by the AJAX call. That's the problem.

How can I make this work? I did know about .on() for bind events on dynamically created elements but I don't know how to fit it on this scenario. The grid is wrapped on a DIV with class and ID and maybe this is helpful or not. Any help?

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

0 Answers0