Ad

AJAX Changing Content Of Page Does Not Work More Than Once?

- 1 answer

I'm trying to load different views without reloading using JQUERY > AJAX. It works fine the first time but the second time it triggers the call and loads the page.

Here is the button I'm using: First time:

<p><a target="_blank" rel="nofollow noreferrer" href="{{ URL::route('onboarding-ajax', ['i' => '2']) }}" id="next-step" next-step-id="2">Start <i class="icon arrow-right"></i></a></p>

Second time:

<p><a target="_blank" rel="nofollow noreferrer" href="{{ URL::route('onboarding-ajax', ['i' => '3']) }}" id="next-step" next-step-id="3" >Next</a></p>

Here is the script:

    <script>
    $('#next-step').on('click', function (e) {
        e.preventDefault();

        var that    = $(this),
            url     = that.attr('href'),
            type    = 'GET',
            step_id = that.attr('next-step-id'),
            width   = (step_id / 32)*100 + '%';

        $.ajax({
            url: url,
            type: type,

            success: function(response) {
                $('#content-wrap').html(response.view);
                window.history.pushState({path:url},'',url);
                return false;
            }
        });
    });
</script>

Any idea what is being done wrong?

Ad

Answer

If your #next-step element is inside #content-wrap, it will disappear when you replace #content-wrap contents. If the new contents also have a #next-step inside it, it is a different element with the same ID, and will not have a click handler attached to it like the previous one did.

The easiest way to salvage it is to use a "live" handler - not on the #next-step, but on a parent. Try this:

$('#content-wrap').on('click', '#next-step', function (e) {

This tells #content-wrap to pay attention to a click event on a #next-step. Since you don't replace #content-wrap itself, this handler will persist, and will catch events even if #next-step is replaced.

Ad
source: stackoverflow.com
Ad