0

Well I have the problem, I can't log out when i just log in (without reloading the page). And I cant log in when I just logged out (again with page reload it works). Well I think after reloading the nav, he forgets the id of logout or something?

<script>

    logout = $('#logout')
    loginform = $('#loginform')

    logout.click(function () {
        $.ajax({
            url: 'accounts/logout/',
            success: function (json) {
                console.log(json)
                });
            },
        });
    });

    loginform.on('submit', function (event) {
        event.preventDefault();
        login();
    });

    function login() {
        $.ajax({
            url: 'accounts/login/',
            success: function (json) {
                console.log(json)
                /* Reloades the navbar */
                $('#usergui').load(document.URL + ' #usergui');
            }
        });
    }
    ;
</script>

My HTML:

<div id="usergui">
    <ul class="nav navbar-nav navbar-right">
        {% if user.is_authenticated %}
        <li><a id="logout"> </span>
                Logout
        </a></li> 
        {% else%}
        <li><a> </span>
                Login
        </a></li>
        <li><a> </span>
                Register
        </a></li> 
        {% endif %}
    </ul>
</div>

After Login my user gets authenticated and reloading the nav make only logout appear. The Element wasn't created dynamicaly-> it's static

2 Answers2

0

As you are reloading the navbar the DOM element are removed and so does there event handler

You can use .on() method with Event Delegation approach

$(document).on('click', '#logout', function() {
    $.ajax({
        url : 'accounts/logout/',
        success : function(json) {
            console.log(json)
            });
        },
    });
});

$(document).on('submit', '#loginform', function(event) {
    event.preventDefault();
    login();
});

In place of document you should use closest static container.

Satpal
  • 132,252
  • 13
  • 159
  • 168
0

You need to "re-add" the onclick event handler to the logout tag after this code executes $('#usergui').load(document.URL + ' #usergui');.

Your script should look something like this:

<script>
function doButtonHandlers(){
    logout = $('#logout');
    loginform = $('#loginform');

    logout.click(function () {
        $.ajax({
            url: 'accounts/logout/',
            success: function (json) {
                console.log(json);
                });
            },
        });
    });

    loginform.on('submit', function (event) {
        event.preventDefault();
        login();
    });
}

function login() {
    $.ajax({
        url: 'accounts/login/',
        success: function (json) {
            console.log(json)
            /* Reloades the navbar */
            $('#usergui').load(document.URL + ' #usergui');
            doButtonHandlers();
        }
    });
};

doButtonHandlers();

Jacques Koekemoer
  • 1,378
  • 5
  • 25
  • 50