Refresh a div with jQuery

27,657

Solution 1

You can dynamically change the contents of the signup div with jquery as follows:

$("#signup").html("My New Login Section");

or

var $loginDiv = $(document.createElement("div")).html("<label>Username</label><input type='text' id='username'/>");
$("#signup").html($loginDiv);

Solution 2

Use load()

$('#signup').load('php/logout.php', function() {
  alert('Logout.');
});
Share:
27,657
nimrod
Author by

nimrod

I am a fullstack developer (PHP, Java, AngularJS, etc).

Updated on July 04, 2020

Comments

  • nimrod
    nimrod almost 4 years

    Is it possible to refresh a single div with jQuery? I have a button that does logout a user. After the button is clicked, I want to show the login form, so I need to re-parse this div.

    The content of my div is this:

    <div id="signup" class="register">
    
        <?php
            $email = $_COOKIE['email'];
            $login = $_COOKIE['login'];
    
            if($email != null && $email != "" && $login != null && $login != "") {
                echo "<h3>you are logged in as <b>$email</b></h3><br><br><button id='logoutbtn' class='submitButton'>Logout</button>";
            } else {
                // show login form
            }
        ?>
    
    </div>
    

    This is my JavaScript part where I perform the logout:

    $('#logoutbtn').click(function () {    
        $.ajax({  
            type: "POST",  
            url: "php/logout.php",  
            async: false,
            success: function(data){
                // reload signup div
            } 
        });  
    });
    

    Edit: My logout.php script removes the cookies, that's why I need to re-parse the signup-div.

  • nimrod
    nimrod almost 11 years
    I think that load() is not the proper way here as the logout script can easily be accessed through AJAX. The question is how to refresh the view after the user has been logged out.
  • nimrod
    nimrod almost 11 years
    This is not exactly what I intended to do but it works. The problem is that I have to add the html code to one variable for the signup form, which is very long.