Skip to content
Advertisement

Best practice for triggering events on calling page from an ajax page

I have a page that lists a bunch of files. This page can be accessed directly via a URL or it can be loaded in a modal dialog via ajax from a different page.

If the files page is loaded via ajax, I would like to allow the user to click the name of the file and trigger an action in the page which loaded the files page. For example, there is an article edit page. This page contains an “attach a file” button. When the user clicks the button, the files page is loaded in a modal dialog and when a filename is clicked, the id of the file is inserted into the article form and the dialog is closed. However there is also an event edit page with a similar button, but I would like to handle the filename-click event slightly differently on this page.

I’d like to handle these click events slightly differently depending on the calling page. At the moment I’m defining a handler function with global scope in the page containing the form to which files are being attached, then testing for that function in the the files-page when the filename is clicked and calling if it exists. It works but it feels a little hacky. Is there some kind of best practice for this sort of thing that I’m not aware of?

I’m using jQuery if this makes things easier in any way..

Answer

You should look at jQuery Live

Attach a handler to the event for all elements which match the current selector, now and in the future.

When a Ajax page is loaded it’s not processed by the DOM in the same way the main page was loaded, therefore using live will attach the event on all current event emitters as well as the future ones such as dynamic Ajax content

Within your Ajax model

<div>
    ...
    <a href="#" id="ajax_click_event">Add to main page</a>
    ...
</div>

and within your static page (the one originally loaded)

$("#ajax_click_event").live('click',function(){
    //Work wit the value of the form within the ajax div.
})
Advertisement