0

I was wondering if there is a way to execute script within a ajax dynamically loaded content. I've searched the web and this forum also an find a lot of answers, like

[Running scripts in an ajax-loaded page fragment [1]: Running scripts in an ajax-loaded page fragment [1]

But none of this seems to work fine for me. I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.

For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:

//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,

$ajax([..]) //THEN 
.ajaxSuccess(function(){     
    // LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
    $(".script_target").each(function()
    {   
      //DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
      //EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
      //WILL FIRE A SCRIPT RELATED TO drop_down CASE.
    });
});

I know this is an ugly solution but i didn't came up with nothing better than this. Can you help to improve this method? Maybe there's a way to let the browser fire script within the loaded page automatically?

PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.

Thanks in advance.

Community
  • 1
  • 1
Ivan
  • 408
  • 4
  • 14
  • Just to make sure, does the element with class ".script_target" exists *before* the ajax call ? Or do you want to load the markup from the server (in which case $.load is your friend ...) ? – phtrivier Mar 15 '12 at 16:18
  • the element .script_target is the div "target" of the script. The script in this case in not loaded dynamically, but fired from the main library. I currently use the .load function to retrieve pieces of html from the server and load it in the homepage. – Ivan Mar 15 '12 at 16:30

4 Answers4

2

If I understand you correctly :

  • you use "load" to retrieve html content from the server, and you add it to the page.
  • later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
  • but, depending on the markup retrieved, you want to do something different in the ajax callback

So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?

Otherwise maybe something like this would work :

  • In the callback of the "$.load" function, use $.data() to attach more information to created dom object
  • In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?

Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.

Hoping this helps.

EDIT : After your comment, it might be related to the selector you use when calling $.load().

There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :

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

Could this be your issue ?

Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).

This way, "loading" a page would be something along the lines of :

$.load("url_of_a_page_markup.html", function () {
  require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
     TheJsModuleForThePage.doSomething();
  });
});

If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.

Hoping this helps.

phtrivier
  • 13,047
  • 6
  • 48
  • 79
  • I think i've explained wrong my problem, il get straight to the point: 1) First i Load the main page from the server as a normal browser request, 2) when the structure of the page is fully loaded i do an ajax call with jquery.load function that retrieve a piece of html from the server and display the new content dynamically. | here occurs the problem | because if in this piece of html there's some script tag that should execute automatically, for example onload, they are just ignored from the browser. – Ivan Mar 17 '12 at 00:54
  • For example this piece of code will not fire in any case when loaded with the other html code. The only thing i can do is to bind this piece of code with onclick, or onload events. Let's say i load a page with a gallery inside, and related scripts, what i'm supposed to do to make everything work correctly? there's lot's of script that need to be fired and others that needs initialization, and i can figure out how to handle all that limited as i am. Thanks very much for your help! – Ivan Mar 17 '12 at 01:07
0

I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).

$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});

To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Button - Icons</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  (function() {
    $('#myButton')                     // My button element
    .button()                          // Initialize it as a JQuery UI button object
    .click(function (){                // Hook up the button click event
        $('#correct')[0].play();       // to play a sound in an <audio> tag
    });
  });
  </script>
</head>
<body>
    This is my help file, this is my code.  This is for reading, this is for fun. 
    <button id="myButton">Button Text</button>
</body>
</html>

The dialog would load and the HTML displayed, but the embedded script did not execute.

I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.

This:

<script>
    (function() {
     ...
    });
</script>

Became:

<script>
    (function() {
     ...
    })();                // Immediately invoke
</script>

Niceness.

wolfstevent
  • 703
  • 8
  • 13
0

If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.

Just_Mad
  • 4,029
  • 3
  • 22
  • 30
  • i currently use this function but still it doesn't fire the script loaded in the html fragment. you can see the a live example in action here: http://isdesign.tv, thanks – Ivan Mar 15 '12 at 16:33
0

Have you considered a module loader like require.js or Lab.js?

There are many other people asking similar questions:

Edit: I think I misread your question. Will try and come up with a better answer. Sorry!

Best of luck to you!

Community
  • 1
  • 1
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50