...

View Full Version : Ajax login doesn't work if the form wasn't present at page load



DR.Wong
02-11-2011, 01:17 PM
Hi all!

I'm having a small problem, I am using the jQuery AJAX login script below. The script works perfectly, however, the form exists on a page called "login.php" which is brought into a div using AJAX when the user clicks on "login".

The login script below exists on the page which retrieves the login form.

The script does not execute if the form wasn't included when the page loaded.

I think it might be the $(document).ready function, but I can't figure out what to change it to.

Can anyone help?


// Developed by Roshan Bhattarai
// Visit http://roshanbh.com.np for this script and more.
// This notice MUST stay intact for legal use

$(document).ready(function()
{
$("#login_form").submit(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
//check the username exists or not from ajax
$.post("modules/login/validator.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Login Successful. Loading...').addClass('messageboxok').fadeTo(900,1,
function()
{
//redirect to the desired destination after login
initialiseAfterLogin();
});

});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Invalid Login Details.').addClass('messageboxerror').fadeTo(900,1);
});
}

});
return false; //not to post the form physically
});
//now call the ajax also focus move from
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
$('#username').focus();
});

venegal
02-11-2011, 04:14 PM
On page load, your code sets up the existing form for submission. If the form isn't there on page load, it will not be set up.

If you're using a current version of jQuery (which you should), you can change

$("#login_form").submit(function(){
// your code
});

to


$("#login_form").live('submit', function(){
// your code
});

That way, every time you add something to the DOM (as opposed to just once on lpage load), it will be checked if it matches the selector, and if so, the event will be set up.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum