Nix
Nix

Reputation: 5998

Run function when submitting form inside Fancybox

I have a link on my page, which calls a login form inside Fancybox. Due to how scoping in the CMS "works", this needs to be called from a different page.

My first idea was to call it with AJAX, but the problem then, was that the page would redirect to the login page on submit, which is not what I want. It should simply refresh the current page.

My second idea then, was to iframe the form in. It's a bit more clumpsy, but seems to do the trick. Upon submit, it only refreshes the view in the iframe, instead of redirecting the user, which is one step forward

However, we still need to refresh the page, so that the content may be updated now that the user is logged in. I've tried binding a function to the .on(click) of the <submit>. I've also tried binding a function to onsubmit on the form itself. I even tried inlining it. Neither seem to do squat.

Should I give up and my dream of being a Javascript developer and fall back on a life of crime, or is there actually a real way to do what I'm trying to do?

I am using Fancybox v1.3 and jQuery v1.7.2.

$('a#myLoginTrigger').fancybox({
    type: 'iframe'      
});


$('form#myForm').on('submit', function(){
    alert('Sweet dude, I can run functions in here!');

    // I assume this will refresh the entire page, not just the iframe
    location.reload();

    // This has no effect whatsoever
    return false; 
});

Upvotes: 0

Views: 1631

Answers (2)

Nix
Nix

Reputation: 5998

This is what I ended up doing:

$('a#loginTrigger').fancybox({
    type: 'ajax',
    href: '/Login.aspx #loginContainer'
});

$('body').on('submit', '#forLogin', function(e) {
    e.preventDefault();

    var url = $(this).attr('action');

    $.post(url, $(this).serialize(), function(data) {
        location.reload();
    })
});

First I use AJAX to load the form on the login page. Then, when the user submits the form, I cancel the default action, and AJAX-post it to the original page, and then reload the whole page.

A strange bug I encountered, was that jQuery couldn't figure out how to post it, if the action URL contains a question mark. To begin with, I tried posting to the page with /?ID=42 (the ID of my login page). The CMS can use both ID and the page title to navigate pages. Using the page title (login.aspx) worked fine.

However, this bug was fixed after updating from jQuery 1.7.2 to 1.8.0. :)

Upvotes: 0

Helge
Helge

Reputation: 833

Try this:

$('a#myLoginTrigger').fancybox({
    type: 'iframe',
    onComplete: function() {
        // Activate the form submit handler here
        $('form#myForm').on('submit', function(){
               alert('Sweet dude, I can run functions in here!');
        })
    }
});

The onComplete callback will be fired as soon as the lightbox is fully loaded. Thus, you can activate the form handling in that function.

Upvotes: 1

Related Questions