maRGen
maRGen

Reputation: 23

ajax received links unclickable

I've been messing around with ajax the last few days and I'm stuck when it comes to keep links clickable.

I have a menu with a few listitems and attached an eventhander in an external javascript file which looks like that:

document.getElementById('home').addEventListener("click", navigate, false);

for all elements. In the navigate function I am using the ajax:

$.ajax({
        type: "POST",
        url: "php/navigation.php",
        data: "clicked=" + this.id,
        dataType: 'json',
        async: false,
        success: function(response) {
            if (response && response.text1 && response.text2) {
                $("#leftContent").html(response.text1);
                $("#rightContent").html(response.text2);
            }
        }
    });

I am using the json datatype so I can seperate the data for two divs #leftContent and #rightContent. now the php file makes some simple queries to get data from a db. however this works fine! the code filled into the html objects works. I'm styling it with css to make it look good and it seems like the solution above is ok.

BUT when I respond with a link in the navigation.php file it's not clickable. so imagine the navigation.php looks like this (simplified)

$content = json_encode(array(
            'text1' => '<a href="127.0.0.1">link</a>"',
            'text2' => 'This text would go in response text 2'
        ));

echo $content;

I tried to just use href="#" and use the onlick method and use a function to handle this but still nothing happens. I did search the net and came across the bind()-method which allows to add and Eventhandler. well I could this but what if I receive a list of links from the php file. some kind of:

$content = json_encode(array(
            'text1' => '<a href="http://...">link</a><br /> <a href="http://...">link</a><br /> <a href="http://...">link</a><br /> ',
            'text2' => 'This text would go in response text 2'
        ));

echo $content;

I can add an event handler to the whole list then but not each single element. is there a simple solution? Using multidimensional arrays as a response and parsing the data would be an idea. Or is there just a simple way to do this?

Upvotes: 2

Views: 183

Answers (1)

cweston
cweston

Reputation: 11647

You can use jQuery on to bind the container, allowing you to maintain your events while replacing the links:

Something like:

$('#leftContent').on('click', 'a', navigate);

Upvotes: 1

Related Questions