views:

94

answers:

4

Hi there,

I'm currently developing a website and i need that the pages loads dynamically based on what actions the user does.

Example: if the user clicks on the button 'Settings' an ajax function will load from an external page the code and will put into the div with tag 'settings'.

This is the code i use to make the Ajax request:

    function get_page_content(page, target_id)
    {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById(target_id).innerHTML = xmlhttp.responseText;
                // After getting the response we have to re-apply ui effects or they
                // won't be available on new elements coming from request.
                $('button').sb_animateButton();
                $('input').sb_animateInput();
            }
        }
        xmlhttp.open('GET', 'engine/ajax/get_page_content.php?page=' + page, true);
        xmlhttp.send();
    }

And this is where the ajax results will be put by first snippet:

<div id="settings_appearance">                
</div>

The code is called from a function here:

<div class="left_menu_item" id="left_menu_settings_appearance" onclick="show_settings_appearance()">
    Appearance
</div>

And this is the html that the ajax function will put into the settings_appearance div:

    <script type="text/javascript">
        $(function()
        {
            $('#upload_hidden_frame').hide();
            show_mybrain();

            document.getElementById('avatar_upload_form').onsubmit = function()
            {
                document.getElementById('avatar_upload_form').target = 'upload_hidden_frame';
                upload_avatar();
            }
        });
    </script>
    <div class="title">Appearance</div>
    <iframe id="upload_hidden_frame" name="upload_hidden_frame" src="" class="error_message"></iframe>
    <table class="sub_container" id="avatar_upload_form" method="post" enctype="multipart/form-data" action="engine/ajax/upload_avatar.php">
        <tr>
            <td><label for="file">Avatar</label></td>
            <td><input type="file" name="file" id="file" class="file_upload" /></td>
            <td><button type="submit" name="button_upload">Upload</button></td>
        </tr>
        <tr>
            <td><div class="hint">The image must be in PNG, JPEG or GIF format.</div></td>
        </tr>
    </table>

I would like to know if there's a way to execute also the javascript code that's returned by the ajax function (upload button in the returncode doesn't work because of this) and if it's possible to apply some customized ui effects i build that are loaded with the main page.

Thanks for helping.

P.S. This is the script that applies the ui effects:

<script type="text/javascript">
// UI effects
$(document).ready(function()
{
  $('button').sb_animateButton();
  $('input').sb_animateInput();
  $('.top_menu_item').sb_animateMenuItem();
  $('.top_menu_item_right').sb_animateMenuItem();
  $('.left_menu_item').sb_animateMenuItem();
});
</script>

P.P.S. Ui effects are not applied to html elements (such as input and buttons) returned by the ajax function. I used a little workaround by applying again ui-effects after ajax function returns the response. Probably there's another way of doing it... the same that will help me solve this problem.

+1  A: 

I recommend you not to, it might lead to a security breach.
If you already use jquery, use it's ajax functionallity instead of the raw one.
When the ajax request completes execute the animation code (just leave it on the page that does the ajax call).

the_drow
A: 

In your content HTML (the one you get from the call) make a common javascript function for every content page, that will be called every time the content is loaded on the master page...

the function name will be something like: loadContentJavascript() {}

and this function is in charge of loading all the functionalities that it will be load on a onload event.

Garis Suero
+2  A: 

I also suggest you don't, but after loading the content in the div, pass the element ID to this function. This will even handle document.write

function do_JS(e){
        var Reg = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
        var match    = new RegExp(Reg, 'img');
        var scripts  = e.innerHTML.match(match);
        var doc = document.write;
        document.write = function(p){ e.innerHTML = e.innerHTML.replace(scripts[s],p)};
        if(scripts) {
            for(var s = 0; s < scripts.length; s++) {
                var js = '';
                var match = new RegExp(Reg, 'im');
                js = scripts[s].match(match)[1];
                js = js.replace('<!--','');
                js = js.replace('-->','');
                eval('try{'+js+'}catch(e){}');
            }
        }
        document.write = doc;
    }

A better solution will be to add a function that you can call at the end of the update to show the effects.

Aaron Harun
Nice!... im not the one who asked, but im going to save this code... :)
Garis Suero
The original question is about a page that's already using jQuery, and jQuery already includes functionality to do exactly this work.
Pointy
His AJAX code isn't jQuery though. I assumed there was some reason for that choice. For example, if it needed it to be library independent.
Aaron Harun
I decided not to use jquery 'cause i wanted to use it only for building ui-effects. But in this case it's very usefull. However if i use '$.get...' i don't need to use the function do_JS in this comment.Thanks for helping.^^
Silvio Iannone
+2  A: 

If you use the jQuery ajax function (or the simplified jQuery get function), and set the datatype to html, then jQuery will evaluate the contents of any script tags included in the results.

Your $.get call would look something like:

$.get('engine/ajax/get_page_content.php?page=' + page,null,function(result) {
    $("#"+target_id).html(result); // Or whatever you need to insert the result
},'html');
ckramer
Ok... i'm gonna try this way. I'll let you know :D
Silvio Iannone
Thanks a lot! This helped me so much!However, i think that this could be very helpful: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Silvio Iannone