defunkt / jquery-pjax

pushState + ajax = pjax
https://pjax.herokuapp.com
MIT License
16.74k stars 1.97k forks source link

Load js function on load #181

Closed mirzadelic closed 12 years ago

mirzadelic commented 12 years ago

I use pjax, and everything works, but 1 thing. When i load content, and js with it, js on load works, but function like this:

var map = {
    init : function() {
        alert('test');
    }

}

map.init

that function is not calling, and ther regular function test() { ... } doesn't work too, why ?

sagarsane commented 12 years ago

Hey,

I don't know if it is a typo, but the init should be called as map.init(); right? Also, a semicolon after '}'. It is working in jsfiddle: http://jsfiddle.net/2cSxW/

var map = {
    init: function() {
        alert('test');
    }

};

map.init();​

Thanks!

mirzadelic commented 12 years ago

Thats right, thanks.

sagarsane commented 12 years ago

Np!

mirzadelic commented 12 years ago

Got new problem like this. I use #main_containter div where are all divs and script with javascrpt code, and i use pjax with this function:

$('a[data-pjax]').pjax({
    container: '#main_container',
    fragment: '#main_container'
});

Now, when i click on link, that #main_container div is replaced with new one, but when i inspect page, i see only divs, there is no <script> tag at all, so javascript is not loaded, why is this happening when i use fragment, without it, it works when leave only main_container div in page that need to be loaded on click ?

sagarsane commented 12 years ago

Can you post your corresponding HTML markup? Or even better if you can put it in JSFiddle , so that it will be easier to see the whole picture :) .. As you say that <script> tag is not visible at all, I am guessing seeing the whole picture will help!

Thanks! Sagar

mirzadelic commented 12 years ago

Here is link: http://fbstatusi.com/desavanja/kalendar/mesecna_lista Check that out, and there are 2 links in main_content, Zurka 123 click, and see what heppens, page is loaded but scripts are not, inspect and view source.

sagarsane commented 12 years ago

Thanks. I checked it out and you are right, scripts are not loaded when I click on it. But it is working if you reload the page, did you check that out? I am not exactly sure, but the problem might be that you have script tags inside #main_content which gets updated when you do a pjax request. This might be resetting that div. I think following might work:

The fact that it is working (getting the alert and the map being loaded) when you reload, makes me think that putting the script tags correctly might solve your issue!

Also, check this link http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup for info on putting script tags in html

mirzadelic commented 12 years ago

I know that, but i need to do in this way, if all my scripts are in 1 file, that will be big file, becouse of that i use script for each page. Yes when reaload it works, just with pjax request it doesn't work. Can i fix this somehow ?

Thanks for answer.

sagarsane commented 12 years ago

Np! Not all your scripts, just the script created by you (the pjax code you had). Did you try putting the script tags outside the #main_container div. This should be ok even if you don't want to have scripts in different file.

Also, you can have 1 JS file for each page (only the JS you write) if you want to keep things modularized. This way, you won't have 1 big file for your custom scripts.

I still think that because you have script tags in #main_container! it does not work on pjax response but works when you reload. Putting them outside that div tag might work. Something like this:

<div id="main_content" class="shadow">
    <ul class="mesecna_lista_ul">
                <li class="datum_linija"><span class="datum_linija_text">11.09. - Utorak</span></li>
                <li class="desavanje_linija"><span class="vreme_linija">01:20h</span> - <a href="http://fbstatusi.com/desavanja/kalendar/desavanje/zurka-123" data-pjax="yes">Zurka 123</a></li>
                <li class="desavanje_linija"><span class="vreme_linija">07:10h</span> - <a href="http://fbstatusi.com/desavanja/kalendar/desavanje/sss" data-pjax="yes">sss</a></li>
    </ul>
</div>
<footer id="page_footer">
        <a href="#" class="big_button">Pošđćčtovanje</a>
        <a href="#" class="button">Pošđćčtovanje</a>
        <a href="#" class="button">asdasdsa</a>
        <a href="#" class="button">asdasdsa</a>
        <a href="#" class="button">asdasdsa</a>
        <a href="#">asdasdsa</a>
</footer>
</div> <!-- For #wrapper -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta6/handlebars.min.js"></script>
<script src="/desavanja/public/js/jquery.placeholder.min.js"></script>
<script src="/desavanja/public/js/jquery.pjax.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script><script src="http://maps.gstatic.com/intl/en_us/mapfiles/api-3/9/13b/main.js" type="text/javascript"></script>
<script>

    $(document).ready(function() {

        $('a[data-pjax]').pjax({
            container: '#main_content',
            fragment:  '#main_content'
        });

    });

</script>
</body>

This might work! Thanks.

mirzadelic commented 12 years ago

But when i load new page, there is javascript code, and i put it in #main_container, becouse pjax will use that div as fragment, to take all from it, becouse of that i use script in div #main_content.

Each page have its javascript code, thats why i use it in body, not in head tag.

sagarsane commented 12 years ago

Were you able to fix this?

AFAIK, it should still be ok if you put it just before the </body> tag but outside the #main_container div .

mirzadelic commented 12 years ago

Yes, it can work in that way, but i cant load script tag for next page, i need to put all scripts in 1 file then, or before to put all my js code.

sagarsane commented 12 years ago

Oh okay. I get it. I will try it out and get back with you!

Thanks. Sagar

sagarsane commented 12 years ago

Hey @mirzadelic , this is wierd but I tried your index page on my local server and it seems to be working fine! But not sure..

mirzadelic commented 12 years ago

Do you use fragment ? If you use fragment it doesn't work on localhost.

sagarsane commented 12 years ago

Yes, I used fragment, infact the exact same markup and scripts as you had in your landing page. The only thing is that the hrefs for anchor tags are still pointing to the server scripts on your server as I didn't setup those because I was running my localhost on WAMP stack.

mirzadelic commented 12 years ago

Can you put it on jsfiddle to check it out ?

sagarsane commented 12 years ago

It is very similar to what you had. Here you go: Working on JSFiddle

mirzadelic commented 12 years ago

It refresh page on jsfiddle, mark text logo at top, then click on link, and that text will be unmarked, becouse it loads new page.

sagarsane commented 12 years ago

Hmm got you. It is doing a normal request. One more thing you could try is when you return the html when you click on zurka 123 , you can try and return only the content you need + the title. If you see the demo page for pjax at http://pjax.heroku.com , the server response does include <html> , etc. It starts with <title>.

sagarsane commented 12 years ago

Ok, I think I got it. Indeed the response should start with <title>

Have your server return this:

<title>Zurka 123</title>
<div id="main_content" class="shadow">
    <section>
                <h1 class="name">Zurka 123<span class="shadow">11.09.2012.</span></h1>
        <div id="description">
            <div id="map">
            </div>
            <div id="description_text">Opis<br />
asd<br />
qwe<br />
a<br />
<br />
asd    asdas     sss<br />
<br />
<br />
asda<br />
wqeq<br />
weq</div>
            <div id="comments">
                <h2 class="info">Komentari: <span class="comments_num">2</span></h2>
                                <article class="comment" id="c_3">
                    <h1 class="c_autor"><a href="/desavanja/user/prikazi/1">Admin istrator</a> <span class="c_datum">(04.09.2012. 22:43:41)</span></h1>
                                        <p>asdasds</p>
                </article>
                                <article class="comment" id="c_4">
                    <h1 class="c_autor"><a href="/desavanja/user/prikazi/1">Admin istrator</a> <span class="c_datum">(05.09.2012. 00:37:39)</span></h1>
                                        <p>sdfds</p>
                </article>
                                                <article class="comment">
                    <p class="warning">Morate biti registrovan clan da bi mogli da komentarišete dešavanje.</p>
                </article>
                            </div>
            <script id="komentar_template" type="text/x-handlebars-template">
                <article class="comment" id="c_{{id}}">
                    <h1 class="c_autor"><a href="/desavanja/user/prikazi/{{user_id}}">{{user_naziv}}</a> <span class="c_datum">({{dodato_datuma}})</span></h1>
                    <span class="c_delete"></span>
                    <p>{{{komentar}}}</p>
                </article>
            </script>
        </div>
        <div id="info">
            <div class="sidebox">
                <h2 class="info">Informacije</h2>
                <ul class="info_ul">
                    <li><span class="label">Mesto:</span><span class="field">eliterasdas</span></li>
                    <li><span class="label">Drzava:</span><span class="field"><a href="/desavanja/kalendar/drzava/5">Srbija</a></span></li>
                    <li><span class="label">Grad:</span><span class="field"><a href="/desavanja/kalendar/grad/0"></a></span></li>
                    <li><span class="label">Adresa:</span><span class="field">Pristin&scaron;ka 15a</span></li>
                    <li><span class="label">Vreme pocetka:</span><span class="field">01:20</span></li>
                    <li><span class="label">Cena:</span><span class="field">100a</span></li>
                    <li><span class="label">Organizator:</span><span class="field">mirza</span></li>
                    <li><span class="label">Kapacitet:</span><span class="field">200a</span></li>
                    <li>
                                                <span class="label">Vrsta dešavanja:</span><span class="field"><a href="/desavanja/kalendar/kategorija/1" class="button">Žurke</a><a href="/desavanja/kalendar/kategorija/2" class="button">Koncerti</a></span>
                    </li>
                </ul>
            </div>
            <div class="sidebox">
                <h2 class="info">Kontakt</h2>
                <ul class="info_ul">
                    <li><span class="label">Korisnik:</span><span class="field"><a href="/desavanja/user/prikazi/1">Admin istrator</a></span></li>
                    <li><span class="label">Telefon:</span><span class="field">063</span></li>
                    <li><span class="label">E-Mail:</span><span class="field"><a href="mailto:mirzadelic1@gmail.com" class="button">Pošalji e-mail</a></span></li>
                    <li><span class="label">Web adresa:</span><span class="field"><a href="http://www.dsgnet.net" class="button" target="_blank">Link</a></span></li>
                </ul>
            </div>
            <div class="sidebox">
                <div class="ad"></div>
            </div>
        </div>
    </section>

<script type="text/javascript">
    $(document).ready(function() {
        alert("asdas");
        var map,
            map_container = document.getElementById("map"),
            markersArray = [];

        var marker = {
            init : function() {
                                var latlng = new google.maps.LatLng(44.022201, 20.908137099999976);

                var myOptions = {
                    zoom: 10,
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }

                map = new google.maps.Map(map_container, myOptions);

                marker.placeMarker(latlng);

            },

            placeMarker : function(location) {

                var map_marker = new google.maps.Marker({
                    position: location,
                    map: map
                });

                markersArray.push(map_marker);

            }

        }

        marker.init();

        $("body").on("click", ".c_delete", function() {

            if (!confirm("Jeste li sigurni da želite da izbrišete ovaj komentar ?")) return;

            var $this = $(this).parent();
            var c_id = $this.attr("id");
            c_id = c_id.replace("c_","");

            $.ajax({
                type: "POST",
                url: "/desavanja/kalendar/izbrisi_komentar",
                data: { desavanje_id : 34, komentar_id : c_id },
                dataType: "json",
                success: function(data) {
                    if (data.status) {
                        $this.slideUp(200, function() { $this.remove(); });

                        var comments_num = $(".comments_num");
                        comments_num.html(parseInt(comments_num.html())-1);
                    } else alert("Greška.");
                },
                error: function(e) {
                    alert("Greška, pokušajte ponovo: "+e.message);
                    comment.val("");
                }
            });

        });

        $("body").on("click", "#dc_btn", function() {
            var comment = $("#comment_text");
            if (comment.val() == "") return;

            $.ajax({
                type: "POST",
                url: "/desavanja/kalendar/dodaj_komentar",
                data: { desavanje_id : 34, komentar : comment.val() },
                dataType: "json",
                success: function(data) {
                    if (data.status) {
                        comment.val("");
                        data.dodato_datuma = new Date(data.dodato_datuma*1000);
                        data.dodato_datuma = formatDate(data.dodato_datuma);

                        var template = Handlebars.compile( $("#komentar_template").html() );
                        $("#comments article:last").before( template(data) );

                        var comments_num = $(".comments_num");
                        comments_num.html(parseInt(comments_num.html())+1);
                    } else alert("Greška, niste registrovani.")
                },
                error: function(e) {
                    comment.val("");
                    alert("Greška, pokušajte ponovo: "+e.message);
                }
            });

        });

        function leadingZero(number) {
            return number < 10 ? "0" + number : number;
        }

        function formatDate(date) {
            return date.getDate() + "." +
                leadingZero(date.getMonth()) + "."+
                leadingZero(date.getFullYear()) + ". " +
                leadingZero(date.getHours()) + ":" +
                leadingZero(date.getMinutes()) + ":" +
                leadingZero(date.getSeconds());
        }

    });
</script>
</div>

and change your javascript to this:


            $(document).ready(function() {
                $('a[data-pjax]').pjax('#main_content');
            });

Won't be able to demo it on JSFiddle as server response is changing here.

Oh, and in your landing page, put some text like On Home indicating the home page ( I put it one of the nav button's Text). This should (hopefully will :) ) work.

mirzadelic commented 12 years ago

Thanks, this can work, but i need to wrap #main_content in new div, and then $('a[data-pjax]').pjax('#thatNewDiv');, becouse there will be two #main_content divs. Now i need to find the way to work with header menu active.

Thank you man.

sagarsane commented 12 years ago

Hmm Np! .. Should be possible. Glad to help!

fari-99 commented 8 years ago

haha, still not understand this. everything works fine, but the js do not load, only response content and title. btw @sagarsane can you explain to me what this issue is? need this.