Jump to content

Where did 'this' go?


delayedinsanity

Recommended Posts

Just some quick background; I'm a PHP developer normally, I'm just learning how to use JS/AJAX (in particular jQuery, loves it), so while this problem has me completely baffled I'm sure it's ridiculously simple.

 

I'm trying to validate a form before it's submitted. Here's a portion of my code that I've mangled together;

 

jQuery(document).ready(function($) {

var form        = $('#setupform');
var user_msg    = $('#user_msg');
var email_msg   = $('#email_msg');
var user_type = 'user';
var email_type = 'email';

$('#user_name').keyup( validateName );
$("#user_email").blur( validateEmail );

form.submit(function(){
	if ( $('#user_name').val() == "Username..." || $('#user_email').val() == "Email..." ) {
		return false;
	} else if( validateName() & validateEmail() ) {
		return true
	} else {
		return false;
	}
});


function validateName() {

	var t = this;

	if ( this.value != this.lastValue ) {
		if (this.timer) clearTimeout(this.timer);
		user_msg.removeClass('error').removeClass('success').html('<img src="/images/ajax-loader.gif" height="8" width="8"/> checking availability...');

		this.timer = setTimeout(function() {
			$.ajax({
				url: '<?php site_url(); ?>/ajax-signup.php',
				data: 'action=user&data=' + t.value,
				dataType: 'json',
				type: 'post',
				success: function (j) {
					user_msg.html(j.msg);
					if ( j.ok == false ) {
						user_msg.removeClass("success").addClass("error");					
						$('#setupform').attr("action", "");
						return false;
					} else if ( j.msg.indexOf("This username is available!") != -1 ) {
						user_msg.removeClass("error").addClass("success");
						$('#setupform').attr("action", "/wp-signup.php");
						return true;
					}
				}
			});
		}, 200); // timer

		this.lastValue = this.value;
	} // if

} // validateSignup

// validateEmail is almost an exact duplicate, omitted for brevity

 

Since these two functions, validateName and validateEmail are nearly identical, it makes no sense to me to have two seperate functions. In PHP this would be dirt simple... pass a string (user or email) to the function and change the field and data internally based on the value.

 

So, with my menial knowledge set (and believe me, I googled the heck out of this and I'm still coming up short), I tried:

 

function validateSignup( vt ) {

    var t = this;

    if ( vt == 'user' ) {
        var tmsg = user_msg;
    } else {
        var tmsg = email_msg;
    }

    if ( this.value != this.lastValue ) {
        if (this.timer) clearTimeout(this.timer);
        tmsg.removeClass('error').removeClass('success').html('<img src="http://images.assets.handmade.loc/images/ajax-loader.gif" height="8" width="8"/> checking availability...');

        this.timer = setTimeout(function() {
            $.ajax({
                url: '<?php site_url(); ?>/ajax-signup.php',
                data: 'action=user&data=' + t.value,
                dataType: 'json',
                type: 'post',
                success: function (j) {
                    tmsg.html(j.msg);
                    if ( j.ok == false ) {
                        tmsg.removeClass("success").addClass("error");                    
                        $('#setupform').attr("action", "");
                        return false;
                    } else if ( j.msg.indexOf("This username is available!") != -1 ) {
                        tmsg.removeClass("error").addClass("success");
                        $('#setupform').attr("action", "/wp-signup.php");
                        return true;
                    }
                }
            });
        }, 200); // timer

        this.lastValue = this.value;
    } // if

} // validateSignup 

 

Amongst a plethora of variations. None of which work. I can get the value of vt just fine, but the rest of the function fails the instant I add it as a parameter, and I'm clueless as to why. Help!

 

Link to comment
Share on other sites

Is the validateSignup function just replacing the validateName and validateEmail functions, meaning are they going to be inside the jQuery ready function? If so, declare the variable vt before calling the function (semi-global). Then, if you need to change it, you can either do it within the jQuery ready function, or using another function.

Link to comment
Share on other sites

I'm not sure where else I can declare it that makes sense though. The code I was using to try and call it looked like this:

 

var user_type = 'user';
var email_type = 'email';

$('#user_name').bind("keyup", function() { validateSignup( user_type ); });
$('#user_email').bind("keyup", function() { validateSignup( email_type ); });

 

Unless I can make a chain out of it somehow? $().vt.val(user_type).keyup( validateSignup ) or something like that?

 

Link to comment
Share on other sites

Hmm. Well, you could create a global JavaScript variable, then change that variable when you make your calls.

 

var vt;

jQuery(document).ready(function($) {

   var form        = $('#setupform');
   var user_msg    = $('#user_msg');
   var email_msg   = $('#email_msg');
   var user_type = 'user';
   var email_type = 'email';

   $('#user_name').keyup( validateName );
   $("#user_email").blur( validateEmail );

   form.submit(function(){
      if ( $('#user_name').val() == "Username..." || $('#user_email').val() == "Email..." ) {
         return false;
      } else if( validateName() & validateEmail() ) {
         return true
      } else {
         return false;
      }
   });


   function validateSignup() {

    var t = this;

    if ( vt == 'user' ) {
        var tmsg = user_msg;
    } else {
        var tmsg = email_msg;
    }

    if ( this.value != this.lastValue ) {
        if (this.timer) clearTimeout(this.timer);
        tmsg.removeClass('error').removeClass('success').html('<img src="http://images.assets.handmade.loc/images/ajax-loader.gif" height="8" width="8"/> checking availability...');

        this.timer = setTimeout(function() {
            $.ajax({
                url: '<?php site_url(); ?>/ajax-signup.php',
                data: 'action=user&data=' + t.value,
                dataType: 'json',
                type: 'post',
                success: function (j) {
                    tmsg.html(j.msg);
                    if ( j.ok == false ) {
                        tmsg.removeClass("success").addClass("error");                   
                        $('#setupform').attr("action", "");
                        return false;
                    } else if ( j.msg.indexOf("This username is available!") != -1 ) {
                        tmsg.removeClass("error").addClass("success");
                        $('#setupform').attr("action", "/wp-signup.php");
                        return true;
                    }
                }
            });
        }, 200); // timer

        this.lastValue = this.value;
    } // if

} // validateSignup 


$('#user_name').bind("keyup", function() {
    vt = 'user';
    validateSignup();
});
$('#user_email').bind("keyup", function() {
    vt = 'email';
    validateSignup();
});

Link to comment
Share on other sites

Ahahaha, I appreciate the help, I got it working! Only wasted half the day, but the results are what counts, I guess.

 

jQuery(document).ready(function($) {

var form        = $("#setupform");
var user_field  = $("#user_name");
var email_field = $("#user_email");

user_field.keyup( function() { validateSignup( this, 'user_msg' ); });
user_field.blur( function() { validateSignup( this, 'user_msg' ); });
email_field.blur( function() { validateSignup( this, 'email_msg' ); });

form.submit(function(){
	if ( user_field.val() == "Username..." || email_field.val() == "Email..." || user_msg == false || email_msg == false )
		return false;
	else
		return true;
});


function validateSignup( t, vfield ) {

	var vmsg   = $('#'+vfield);
	var action = vfield.substr(0,vfield.length-4);

	if ( t.value != t.lastValue ) {
		if (t.timer) clearTimeout(t.timer);
		vmsg.removeClass('error').removeClass('success').html('<img src="http://images.assets.handmade.loc/images/ajax-loader.gif" height="8" width="8"/> checking availability...');

		this.timer = setTimeout(function() {
			$.ajax({
				url: '<?php site_url(); ?>/ajax-signup.php',
				data: 'action=' + action + '&data=' + t.value,
				dataType: 'json',
				type: 'post',
				success: function (j) {
					vmsg.html(j.msg);
					if ( j.ok == false ) {
						vmsg.removeClass("success").addClass("error");					
						$('#setupform').attr("action", "");
						window['' + vfield] = false;
						return false;
					} else if ( j.msg.indexOf("is available!") != -1 ) {
						vmsg.removeClass("error").addClass("success");
						$('#setupform').attr("action", "/wp-signup.php");
						window['' + vfield] = true;
						return true;
					}
				}
			});
		}, 200); // timer

		t.lastValue = t.value;
	} // if

} // validateSignup

});

 

I had planned to wait until Pro PHP and jQuery was released to learn all of this, but holy hannah today was an eye opener. :)

 

 

Link to comment
Share on other sites

Yeah, I've been a JS programmer longer than a PHP programmer. But I just recently started using jQuery, and I'm still getting the hand of how it does things. It's a great tool, but good JS skills will help tremendously.

 

Good luck on your future projects!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.