l3aronsansgland
l3aronsansgland

Reputation: 344

Generated anchor links in ajax not working

Problem: I have a which is filled via Ajax. There are some local anchors which are created in this table. When an anchor is clicked, it is supposed to turn a which is hidden to visible and scroll to it automatically. All of this is working when I am filling my by hand (visibility + scroll), but not at all when the is filled via Ajax.

I have the following structure in my index.php file:

<section id="section1">
   <table></table>
</section>

<section id="section2>
   (this section is hidden via CSS)
</section>

<!-- When the link "More infos" is clicked -->
<script>
    $('.moreInfos').click(function() {
        if ($('#section2').is(':hidden')) {
            $('#section2').slideDown('slow');
        }
    });
</script>

<!-- Ajax call -->
<script language="JavaScript">

        function createInstance()
        {
            var req = null;
            if (window.XMLHttpRequest)
            {
                req = new XMLHttpRequest();
            } 
            else if (window.ActiveXObject) 
            {
                try {
                    req = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e)
                {
                    try {
                        req = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) 
                    {
                        alert("XHR not created");
                    }
                }
                }
            return req;
        };

        function storing(data)
        {
            var element = document.getElementById('banques');
            element.innerHTML = data;
        }

        function submitForm()
        { 
            var req =  createInstance();
            var montant = document.getElementById("montant").value;
            var mois = document.getElementById("selectMois").value;
            var taux = '<?php echo $taux; ?>' ;
            var data = "taux=" + taux +  "&montant=" + montant+  "&mois=" + mois+"&tag=" + 1;

            req.onreadystatechange = function()
            { 
                if(req.readyState == 4)
                {
                    if(req.status == 200)
                    {
                        storing(req.responseText);  
                    }   
                    else    
                    {
                        alert("Error: returned status code " + req.status + " " + req.statusText);
                    }   
                } 
            }; 

            req.open("POST", "fonction/table.php", true); 
            req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.send(data); 
        } 

</script>

The "Simulate" link calls a php file in ajax which will load the table. Here is the php file called in Ajax :

<?php
    include('BDD.php');
    echo'   <tr>
                <th></th>
                <th>Banque</th>
                <th>Taux</th>
                <th>Frais</th>
                <th>Mensualité</th>
                <th>Plus d\'infos</th>
            </tr>';
    $tag=1;
    $sql="select * from banque where BAN_change=0 and BAN_tag=".$_POST['tag']." ORDER BY BAN_Ordre";
    $select=$bdd->query($sql);
    $result=$select->fetchAll();

    $nb=count($result);
    if ($nb!=0){
        foreach($result as $value){
            $taux=$_POST['taux']+$value['BAN_Taux_Credit'];
            $mensu=$_POST['montant']/$_POST['mois'];
            $mensu+=$mensu*$taux/100;

            echo'<tr>';
                echo'<td><img width="50" height="20" src="img/'.$value['BAN_Id'].'/img.jpg" /></td>';
                echo'<td>'.$value['BAN_Nom'].'</td>';
                echo'<td>'.$taux.'</td>';
                echo'<td>'.$value['BAN_Frais'].'</td>';
                echo'<td>'.$mensu.'</td>';
                echo('<td><a href="#section2" class="moreInfos">More infos</a></td>');
            echo'</tr>';
        }
    }
?>

Summary: When the user clicks on "More infos", the #section2 is supposed to appear and the browser window scrolls to it. Now this is working perfectly when I fill the by hand. Then the #section2 is showing and the browser is scrolling to the #section2. When I am doing it via Ajax, the anchors are not working anymore.

Thanks

Upvotes: 0

Views: 162

Answers (2)

Tez Wingfield
Tez Wingfield

Reputation: 2251

This maybe due to the HTML not being loaded into the DOM. Please try using:

$(document).on('click', '.selector',  function() {
      alert("Working");
    });

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page."

If this works then you can fine tune it afterwards.

Regards,

Upvotes: 1

epascarello
epascarello

Reputation: 207521

Because events do not magically get attached when you add new ones

$('.moreInfos').click(function() {
    if ($('#section2').is(':hidden')) {
        $('#section2').slideDown('slow');
    }
});

Your code needs to use event delegation

$(document).on("click", '.moreInfos', function() {
    if ($('#section2').is(':hidden')) {
        $('#section2').slideDown('slow');
    }
});

Upvotes: 1

Related Questions