phpjqueryajaxfancybox

jquery fancybox login box not load external php file


I am trying to use Fancybox to display the login form like bellow

<div style="display:none">
    <form id="login_form" method="post" action="">
            <p id="login_error">Please, enter data</p>
        <p>
            <label for="login_name">Login: </label>
            <input type="text" id="login_name" name="login_name" size="30" />
        </p>
        <p>
            <label for="login_pass">Password: </label>
            <input type="password" id="login_pass" name="login_pass" size="30" />
        </p>
        <p>
            <input type="submit" value="Login" />
        </p>
        <p>
            <em>Leave empty so see resizing</em>
        </p>
    </form>
</div>  

the javascript for that is

$("#login_form").bind("submit", function() {

    if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
        $("#login_error").show();
        $.fancybox.resize();
        return false;
    }

    $.fancybox.showActivity();

    $.ajax({
        type        : "POST",
        cache   : false,
        url     : "login.php",
        data        : $(this).serializeArray(),
        success: function(data) {
            $.fancybox(data);
        }
    });

    return false;
});

the HTML is

<a id="tip5" title="Login" href="#login_form"><?php echo "Login" ; ?></a>

when I click on the login link, it shows the login popup, but when i click on submit button, it closes the popup and refreshes the page.

actually, it should check the data and display data on the popup, not the refresh page.


Solution

  • There could be more problems:

    1. Fancybox is probably cloning the original HTML to put it into the popup. Therefore You need to use function live instead of bind.
    2. It is possible that Fancybox could alter the form's ID in some way (check that with some DOM Inspector like FireBug for FireFox) and assure that the form's ID within a popup is the one You'd lived the submit event for.

    I also prefer to use event.preventDefault() instead of returning false... My JS code would then be:

    $("#login_form").live("submit", function(e) {
        e.preventDefault();
        if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
            $("#login_error").show();
            $.fancybox.resize();
            return false;
        }
    
        $.fancybox.showActivity();
    
        $.ajax({
            type        : "POST",
            cache   : false,
            url     : "login.php",
            data        : $(this).serializeArray(),
            success: function(data) {
                $.fancybox(data);
            }
        });
    });