Html php Java Script Class not Work Dynamically by Ajax

Question from beginner.

I just try made photo gallery website by sample site template. My photos located in local folder to IIS server.

First job is to load all subfolders from mainfolders: This works fine!

<li class="colorlib-active">
   <?php
    if ($handle = opendir('images')) {
          while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != ".." && $entry != ".htaccess" && $entry != ".htpasswd"){                                 
             echo '<a href="#" onclick=photogallery("images/'.$entry.'")> '.$entry.'</a><br>';                                                                          }
           }
         closedir($handle);
       }                                              
    ?> 
</li>

Then function photogallery(): after cliking subfolder, then we can find all jpg-files and attribute them. This works also fine!

    <script>   
    function photogallery($dir){
        $.ajax({
          url: $dir,
          success: function(data){ 
                $(data).find('a[href$=".jpg"]').each(function () { 
                var filename = this.href.replace(window.location.host, "").replace("https://", "");
                var fileurl = filename;
                var para = document.createElement("div");
                para.setAttribute("class", "col-md-4 ftco-animate");                       
                var para2 = document.createElement("a");
                para2.setAttribute("href",  filename);                       
                para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");                       
                para2.setAttribute("style", "background-image: url("+fileurl+");");                                              
                document.getElementById("photoplace").appendChild(para).appendChild(para2);                
            });
          }
        });
    }             
    </script>

This updates dynamically div photoplace:

<section class="ftco-section-2">
    <div class="photograhy">
        <div class="row no-gutters" id="photoplace">
         </div>                                                                                
        </div>
</section>

So problem is, pictures does not showing in page because class ftco-animate won’t work. I remove this class and now i see pictures. After cliking picture class image-popup won’t work.

Still if i call directly function without ajax:

<script>   
function test($dir2){
      var para = document.createElement("div");
      para.setAttribute("class", "col-md-4 ftco-animate");                       
      var para2 = document.createElement("a");
      para2.setAttribute("href",  $dir2);                       
      para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");                       
      para2.setAttribute("style", "background-image: url("+$dir2+");");                                              
      document.getElementById("photoplace").appendChild(para).appendChild(para2);       
    }       
</script>

By call: test("images/folder1/IMG_20200410_0128.jpg"); This works fine!

Could you please tell what happend code inside ajax or where this is going wrong? Thanks.

Chrome console show following errors:

js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:126 Uncaught pd {message: "Map: Expected mapDiv of type Element but was passed null.", name: "InvalidValueError", stack: "Error↵    at new pd (https://maps.googleapis.com/m…init (myurladdress/js/google-map.js:44:15)"}message: "Map: Expected mapDiv of type Element but was passed null."name: "InvalidValueError"stack: "Error↵    at new pd (https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:56:227)↵    at Object._.qd (https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:56:337)↵    at new Gi (https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:126:50)↵    at init (myurladdress/js/google-map.js:44:15)"__proto__: Error
Gi @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:126
init @ google-map.js:44
load (async)
_.N.addDomListener @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:184
(anonymous) @ google-map.js:62
DevTools failed to load SourceMap: Could not load content for myurladdress/js/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for myurladdress/js/bootstrap.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for myurladdress/js/aos.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for myurladdress/css/aos.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
util.js:230 Google Maps JavaScript API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required
uz.o @ util.js:230
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:140
Promise.then (async)
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:140
setTimeout (async)
Aj @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:140
google.maps.Load @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:14
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:233
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:233

and:

throw _.qd("Map: Expected mapDiv of type Element but was passed "+a+".");if("string"===typeof a)throw _.qd("Map: Expected mapDiv of type Element but was passed string '"+a+"'.");var d=b||{};d.noClear||_.Bi(a);var e="undefined"==typeof document?null:document.createElement("div");e&&a.appendChild&&(a.appendChild(e),e.style.width=e.style.height="100%");if(!(_.z.devicePixelRatio&&_.z.requestAnimationFrame||_.Tg[43]))throw _.P("controls").then(function(m){m.Oh(a)}),

Update! Please forget previous and after many hours of checking i have one question!

What difference is next two ways make function call? (because last one works propely!)

<script>
function loadimages(){
        $imurl ="photos/gallery1/IMG_20200410_0128.jpg";
                    var para = document.createElement("div");
                    var para.setAttribute("class", "col-md-4 ftco-animate");                       
                    para2 = document.createElement("a");
                    para2.setAttribute("href", $imurl);                       
                    para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");                       
                    para2.setAttribute("style", "background-image: url('"+$imurl+"');");                                              
                    document.getElementById("photoplace").appendChild(para).appendChild(para2);       
}

document.getElementById("clickMe").onclick = function () { loadimages(); };          
</script>

or

<script>
function loadimages(){
        $imurl ="photos/gallery1/IMG_20200410_0128.jpg";
                    var para = document.createElement("div");
                    var para.setAttribute("class", "col-md-4 ftco-animate");                       
                    para2 = document.createElement("a");
                    para2.setAttribute("href", $imurl);                       
                    para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");                       
                    para2.setAttribute("style", "background-image: url('"+$imurl+"');");                                              
                    document.getElementById("photoplace").appendChild(para).appendChild(para2);       
}

loadimages();         
</script>

Really, why this last code working properly and html button can’t activate function propel?

This Post Has One Comment

  1. No Fault

    As of jQuery 1.7 you should use jQuery.fn.on with the selector parameter filled:

    $(staticAncestors).on(eventName, dynamicChild, function() {});
    Explanation:

    This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild). When there is a match then your custom handler function is executed.

    Prior to this, the recommended approach was to use live():

    $(selector).live( eventName, function(){} );
    However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

    $(selector).live( eventName, function(){} );
    … can be replaced with the following on() signature:

    $(document).on( eventName, selector, function(){} );
    For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don’t bind to the dynamic content), this can be (and the easiest option) is document. Though bear in mind document may not be the most efficient option.

    $(document).on(‘mouseover mouseout’, ‘.dosomething’, function(){
    // what you want to happen when mouseover and mouseout
    // occurs on elements that match ‘.dosomething’
    });
    Any parent that exists at the time the event is bound is fine. For example

    $(‘.buttons’).on(‘click’, ‘button’, function(){
    // do something here
    });
    would apply to

    <!– s that are generated dynamically and added here –>

Leave a Reply