1

i have a problem i'm loading page in my div using ajax here is a code

Html

<div id="body"></div>
<a class='olink' href='#'>page name</a>

script

$('.olink').on('click',function(e){ 
    var link = this.href;
    $.ajax({ 
        url: page, 
        type:'POST', 
        data : name, 
        success: function(resp){ 
            $("#body").html(resp); 
        } 
        e.preventDefault();  
    }); 
});

The above code working fine and load page in my div, now problem is when i click on any link from loaded page this script not working... currently i add my script in the bottom of main page,, should i add this script on every page?

azro
  • 53,056
  • 7
  • 34
  • 70
Joe
  • 57
  • 1
  • 9
  • Possible duplicate of [jQuery .load() / .ajax() not executing javascript in returned HTML after appended](https://stackoverflow.com/questions/16352371/jquery-load-ajax-not-executing-javascript-in-returned-html-after-appende) – Ruan Mendes Jul 17 '17 at 14:40
  • Add any common scripts like that to a separate JavaScript file and include that with every page. That's far better than copy/pasting the same code onto multiple pages. – krillgar Jul 17 '17 at 14:40
  • Scripts don't execute when setting them with `$.html()` (or with innerHTML for that matter) – Ruan Mendes Jul 17 '17 at 14:40

2 Answers2

0

Script Execution

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. 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. An example of both cases can be seen below:

Here, any JavaScript loaded into #a as a part of the document will successfully execute.

$( "#a" ).load( "article.html" );

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

$( "#b" ).load( "article.html #target" );

you can also you can use $.getScript("url"); to get script or eval youe source like eval(source)

Ebrahim Poursadeqi
  • 1,776
  • 2
  • 17
  • 27
0

If I understand you correctly and you are trying to get your script to fire when clicking on a link from within the #body element then you need to use a delegated event handler:

$('#body').on('click', '.olink', function() {
  var link = this.href;
    $.ajax({ 
        url: page, 
        type:'POST', 
        data : name, 
        success: function(resp){ 
            $("#body").html(resp); 
        } 
        e.preventDefault();  
    }); 
});
AGB
  • 2,378
  • 21
  • 37