0

This question is different from those asked. I have a page named page_1 which only loads information from page_2 into page_1 when a link is clicked. But it only loads the information within a specific div without reloading the page. Sometimes that information contains a JavaScript that must be executed but with jquery load, the information within the div is loaded but the JavaScript is not executed.

Page_1.php

<a href="page_2.php" rel="charger_partiel" data-direction="id_du_milieu" data-ajax_id_to_update="id_du_milieu_2" data-afficher_espace_de_chargement="Oui" data-id_image_de_chargement_devant_lien="devant_charger_partiel">charger_partiel <span id='devant_charger_partiel'></span> </a><br><br>

<div id="id_du_milieu_2">Le text affiche par defaut</div>

<script>

$(document).on('click', 'a[rel*=charger_partiel]', function(f) { 

f.preventDefault();
        
var myId_to_update_here = $(this).data('ajax_id_to_update');    

var myId_to_load_from_other_page = $(this).data('direction');       
        
    var afficher_chargement = $(this).data('afficher_espace_de_chargement');
    
    var id_chargement_devant_lien_partiel= $(this).data('id_image_de_chargement_devant_lien');
     
    var pageURL=$(this).attr('href');
     
     
    history.pushState(null, '', pageURL);
     
    
    var image_de_chargement = '<img src="images/facebook_style_loader.gif" />';
    
    var preloader_comme_facebook_et_youtube = image_de_chargement ;     
        
    if(id_chargement_devant_lien_partiel!='')
    {
        $('#'+id_chargement_devant_lien_partiel).html(image_de_chargement);
    }
     
        
        
    if(afficher_chargement=='Oui')
    {
        $('#'+myId_to_update_here).html(preloader_comme_facebook_et_youtube);
    }
     
    
  $('#'+myId_to_update_here).load($(this).attr('href')+' #'+myId_to_load_from_other_page, 
  
  function(responseText, textStatus, XMLHttpRequest) {
            if(textStatus == 'error') {
                $('#'+myId_to_update_here).html('<p>Oupps.. There was an error making the AJAX request. Maybe your internet connection is slowing down.</p>');
            }
             
      
        });
        
    //Apres le chargement, on enleve le loading
    if(id_chargement_devant_lien_partiel!='')
    {
        $('#'+id_chargement_devant_lien_partiel).html('');
    }
    //Fin de l'affichage du chargement si l'id du span du devant lien est mis
      
  return false;
});
</script>

Page_2.php

<h3 id="id_du_milieu">
Anything from here should be loaded

<div id="id_de_test">id_de_test</div>
 
<div id="id_de_gloire">id_de_gloire </div>

<script> alert('This is a test that should be executed'); </script>

 And it ends here 
</h3>

<h1>This should not be loaded</h1>

<script> alert('This also should not be executed'); </script>

The page loads infos from the other page with <h3 id="id_du_milieu"> , however it doesn't execute the javascript alert.

How to execute only the script that is between the selected id from the other page which in this case is id="id_du_milieu"?

Md. Fazlul Hoque
  • 15,806
  • 5
  • 12
  • 32
Man Of God
  • 774
  • 2
  • 14
  • 32
  • Please see: https://api.jquery.com/load/ *If `.load()` is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.* – Twisty Sep 06 '21 at 22:36
  • Possible duplicate of https://stackoverflow.com/questions/5519792/how-to-load-script-with-jquery-load – Twisty Sep 06 '21 at 22:38
  • @Twisty I had already tried that out but it did not working since my scripts are not in a span. Please do you have a solution ? – Man Of God Sep 06 '21 at 23:53
  • @Twisty When I use the method above I get the following error Uncaught SyntaxError: unexpected token: ':' and when I click on learn more it shows Error: Incorrect contents fetched, please reload. That means that that method does not allow correct fetching – Man Of God Sep 07 '21 at 00:43

2 Answers2

1

Try the following:

var script = $('#id_du_milieu script').text().
eval(script);

Inserted into your source snippet:

$('#' + myId_to_update_here).load($(this).attr('href') + ' #' + myId_to_load_from_other_page,
    function (responseText, textStatus, XMLHttpRequest) {
        if (textStatus == 'error') {
            $('#' + myId_to_update_here).html('<p>Oupps.. There was an error making the AJAX request. Maybe your internet connection is slowing down.</p>');
        }
        else {
            var script = $('#id_du_milieu script').text();
            eval(script);
        }
    }); 
BergListe
  • 388
  • 3
  • 12
1

Consider creating your own Load that can handle the Script portion of the resulting HTML.

// **Snippet is just an Example and will not execute due to CORS**

$.fn.myLoad = function(url, target, callback) {
  var htm;
  var script = $("<script>");
  $.get(url, function(results) {
    if (target != undefined) {
      // Load the entire page and seek out the target
      htm = $(results).find(target).html();
    } else {
      htm = results;
    }
    // Seek for Script in the HTML, if more than 1, this can fail
    script.append($(htm).find("script").html());
    // Strip it from HTML
    $(htm).find("script").remove();
  });
  $(this).append(htm);
  $(this).append(script);
  if (callback != undefined) {
    script.ready(callback);
  }
}

$(function() {
  $("#results").myLoad("https://example.com", "body");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results"></div>

Discussed further here: https://blog.kevinchisholm.com/javascript/jquery-getscript-alternatives/

Twisty
  • 30,304
  • 2
  • 26
  • 45