Hi.

I'm using AJAX to make a menu for a guy's website I'm making for him. Anyway, he has a sports memorabilia store. I have a simple menu. There is a drop down box that you click on to select the sports league you want. Then below it is another drop down box where you choose the conference ex: Big Ten/Big 12/etc for NCAA, NFC/AFC for NFL, etc. The conferences to choose from are automatically set depending on what league you choose. Then after you choose the conference, the teams in that conference show up below it as links you can click on that will take you to the merchandise pages for those teams.

Ok, everything works great...except when you reload the page.

I use sessions to store the league and conference variables. The league and conference selections remain in the menu when you reload the page. (I execute the javascript functions during the load event for the menu.php page)

But in the mother page, menu.php, there is a <span> section. The php pages that are executed by the javascript functions when events are triggered show their output within the span section.

I am going to call the php scripts that are ran from javascript (which show their output in span) span pages because I don't know what else to call them. If there is a real term for them, please correct me of that.


I have found that I cannot execute javascript functions in these span pages, nor can I use html page events such as onload. They just don't seem to be useable by these span pages. I

I cannot show the list of teams this way if you reload the page because of this problem. I was wondering how I could execute javascript from within these span pages.

Thanks.

Dani AI

Generated

Short answer: injected HTML fragments aren't full pages, so browser page-level events and script execution behave differently — inline onload or <script> inside a fragment inserted via innerHTML usually won't run, and "View Source" only shows the original served HTML. is correct that an AJAX update is not a page load; 's session idea is a good route to restore state on a full refresh.

Practical options that fix this reliably:

  • Move behavior into the parent JS and run a small initializer after you inject the fragment. Prefer event delegation (one handler on the container) so newly inserted links just work without reattaching handlers.
  • For a true "comes back on refresh" UX, render the teams server-side when sessions exist (so the HTML is present on initial load), or have your parent page call the same AJAX function during DOMContentLoaded to repopulate the span automatically (this is the pragmatic application of 's suggestion).
  • If you must execute script tags that come from the server, extract them from the response and create real <script> elements so the browser executes them. Avoid eval() and be careful about XSS — only run server-provided scripts you trust.

Example injection pattern (call your wiring function after injection):

function insertFragment(container, html) {
  container.innerHTML = html;
  var scripts = container.querySelectorAll('script');
  for (var i = 0; i < scripts.length; i++) {
    var s = document.createElement('script');
    if (scripts[i].src) s.src = scripts[i].src;
    else s.text = scripts[i].textContent;
    document.head.appendChild(s);
  }
  initMenu(container); // attach listeners or let delegation handle it
}

Quick troubleshooting: use the browser inspector (not view-source) to inspect the live DOM and console logs, confirm whether your initializer runs after injection, and remove any <html>/<body> tags from fragments. If sessions are used to persist selections, either server-render or replay the AJAX on load so the UI is rebuilt consistently after a refresh.

Recommended Answers

All 6 Replies

Not sure if this is relevant, but I also have found that the html code that is outputted from the span pages is not shown when I view the source of menu.php. I viewed the source to check, so I don't even know if you can use <body> tags, because if they are not echoed to the browser, then the onload event might not even work. Is this why it isn't executing javascript functions? I even tried a simple one that showed an alert dialog box which didn't even work, but it works on a normal regular page that is not within a span.

If you are pulling data from the server on fly using Ajax, you can't use events like onload since there is as such no page refresh / loading happening here. This is the very reason why the dynamic content can't be seen in the static source. To view the modified document as and when it changes, use Firebug, a Firefox plugin for Javascript debugging.

If using Ajax, you can make use of the onreadystatechange event listener to make the required updates to the DOM tree.

//some wrapper function which returns XHR object
xhr = getXMLHttpRequestObject();
xhr.open('GET', someURL, true);
xhr.onreadystatechange = function() {
  // The response is ready
  if(xhr.readyState == 4) {
    // The request completed successfully
    if(xhr.status == 200) {
      var data = xhr.responseText;
      // do something with this data which modifies the DOM
    }
  }
};
xhr.send(null);

The conclusion here being that unless you are following the traditional request / response model for pulling in data, your onload event will be fired only once. Ajax requests don't trigger an onload .

Thanks a lot for your reply, S.O.S. I'm confused, though. Should I make this an entire function by itself, or add it to one that already exists in my .js file?

Thanks,
Diode

What I would do is use sessions in the scripts that the ajax calls are referencing. When you refresh your current page, those sessions will then reflect the last file, or set of files(depending on how complicated your ajax application is) and you can populate your javascript with the php sessions. Make sense?

For example:
I have index.php with a ajax call to ajaxfunc.php. I like to make my ajax calls all to one file with several functions written in it and reference the function that I want through the header call from ajax. Anyway, I would, create session array of all the functions that I have called to populate index.php. If I overwrite a section, I replace that section in my session array with the new function call that I overwrote it with. Then, I populate a javascritpt array inside of index.php with php using my session array, then I create a javascript function to loop through that array calling each function that populates my page. Hmm?

You're saying that you only use one php page that the ajax references, instead of multiple?

That's just what I do, you certainly don't have to to apply the session array concept. But just like many people group functions into a functions.php file, I do the same with ajax. It actaully consists of another function file for security and a small class for parsing the variables. Then I query that file with ajaxfunc.php?func1=funcname1&func2=funcname2&func3=funcname3&func4=funcname4 etc... &variable list continues after that. I actually have it set up to sense not only get requests but also post and session possibilities too. This process requires lot more input and environment validation to prevent header injection and other types of hijacking, but it is an organized system and I feel that my ajax is more organized because of it. I actually got the idea from a post on daniweb.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.