General Question

lefteh's avatar

Executing JavaScript in a page retrieved using AJAX?

Asked by lefteh (9429points) February 28th, 2009

Page A includes AJAX navigation/content. Page B is one of the pages that will be retrieved by the AJAX in Page A. Page B includes some JavaScript, which obviously won’t be executed when loaded into Page A via AJAX. How can I get that JavaScript to execute? I’ve been experimenting with eval() for a while to no avail.

Observing members: 0 Composing members: 0

8 Answers

aeschylus's avatar

Would assigning the scripts in page B to an “onload” event handler not work? (I’m new to this, but that seems possible. Forgive my kneejerk response.)

lefteh's avatar

No, because when Page A pulls Page B, it’s loading pure text (basically), without any scripts being evaluated. Or so I believe.

funkdaddy's avatar

Put your javascript in the main page and make it event based.

For instance you can run it as part of your code executed when your ajax is done loading the inserted content. This is done a little differently depending on if your using a library or not, but whatever you’re doing should have a section that runs once that content is successfully retrieved and inserted.

Will that work in your situation?

Vincentt's avatar

I’m not sure if you’re using jQuery, but when I was having this problem I solved it with the livequery plugin for jQuery (though I believe something like this will be integrated into jQuery).

lefteh's avatar

I am using jQuery, actually. I’ll give that a try. Thanks!

lefteh's avatar

Okay, it’s a start. Here’s the deal: the home page of the site features a table that I am using jQuery’s Tablesorter plugin to interactively sort. With livequery, the sorting function works when the page is initially loaded, but if I navigate to a different page using the AJAX navigation and then navigate back to the page with the table, the sorting function no longer works. Here is the code in the header of the index page. Any ideas?
I’m pretty new to jQuery, FYI.

Vincentt's avatar

Heh, well, I can hardly imagine you’re newer to it than I am – I’ve hardly used it at all and that without even knowing Javascript :P

I found out about it in the #jquery IRC channel on Freenode, so if you use IRC be sure to check that out to get some help with this. I really didn’t get it right the first try either.

Anyway, why are you referring to $(”.tablesorter”) within $(’#admin_main_table’)? It’s been a while since I did that thing with livequery, but here’s what I did: http://pastie.org/405001

funkdaddy's avatar

did you get this squared away?

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther