开发者

pass 2 variables from 1 function to another in jquery

OK, I'm getting the results of a PHP form from JSON to do a login validation. I want to check to see if their account is activated, which I do just fine. If it's not I show a jQuery error but I want the ability to let them resend the activation email. I can pass the username password to the function displaying the error with JSON, but how do I then pass that data to a new function to process the new email? Here is what I have so far:

// LOGIN Valida开发者_StackOverflow中文版tion

$(function(){
  $("#jq_login").submit(function(e){
     e.preventDefault();  

     $.post("widgets/login_process.php", $("#jq_login").serialize(),
       function(data){    
        if(data.all_check == 'invalid'){
          $('div.message_error').hide();
          $('div.message_success').hide();
          $('div.message_error').fadeIn();
          $('div.message_error').html(
            "<div>UserId and/or password incorrect. Try again.</div>"
          );

        } elseif(data.user_check == 'invalid'){
          $('div.message_error').hide();
          $('div.message_success').hide();
          $('div.message_error').fadeIn();
          $('div.message_error').html(
            "<div>UserId and/or password incorrect. Try again.</div>"
          );

        } elseif (data.activated_check == 'invalid'){
          $('div.message_error').hide();
          $('div.message_success').hide();
          $('div.message_error').fadeIn();
          $('div.message_error').html(
            "<div>Your account has not been activated. Please check your "  + 
            "email and follow the link to activate your account. Or click " +
            "<a href='#' id='resend'>here</a> to re-send the link.</div>"
          );

        } else {
          $('div.message_error').hide();
          $('div.message_success').fadeIn();
          $('div.message_success').html(
            "<div'>You are now logged in. Thank you </div>"
          );

          window.location.replace("producer.php");
          return false;
        }
      }, "json");
    });
  });             

  $(function(){
    $("#resend").live('click', function(event){
      event.preventDefault();
      alert(data.username);

      var data = 'username=' + data.username + 'password=' + data.password;

      $.ajax
    });                  
  });

I'm new so I don't understand all the ins and outs of passing data back and forth.

thank you.

craig


With Ajax there's not really "passing data back and forth," but rather just passing callbacks. That's what you're doing when you put function() { ... } as a function parameter--you're creating a callback.

I think the best course of action is to refactor this into several stand-alone functions. A good best practice is to make each function do one thing only, rather than defining functions within functions within functions.

Once refactored, it becomes more clear how we can "reuse" the username and password for the resend-activation link.

(function() { // to keep these functions out of the global scope(†)
  // this will be called when the login form is submitted
  function handleLogin(evt) {
    evt.preventDefault();

    // same as your code except that instead of creating a function here
    // we instead pass `handleLoginResponse`, which is a function we'll
    // define later
    $.post( 'widgets/login_process.php',
      $(this).serialize(), // <-- In events, `this` refers to the element that 
      handleLoginResponse, //     fired the event--in this case the form, so we
      'json'               //     don't need its id, we can just give `this`
    );                     //     to jQuery.
  }

  // This is the function we gave to $.post() above, and it'll be called when
  // the response is received.
  function handleLoginResponse(data) {
    // Here we decide what message to show based on the response, just like
    // in your code, but we call a function (showError or showSuccess) to
    // avoid repeating ourselves.
    if(data.all_check == 'invalid') {
      showError("UserId and/or password incorrect. Try again.");

    } else if(data.user_check == 'invalid') {
      showError("UserId and/or password incorrect. Try again.");

    } else if(data.activated_check == 'invalid') {
      showError("Your account has not been activated. Please check your " + 
                "email and follow the link to activate your account. Or " +
                "click <a href='#' id='resend'>here</a> to re-send the link."
      );

    } else {
      showSuccess("You are now logged in. Thank you.");
      redirectToLoggedInPage();
    }
  }

  // the function that shows error messages
  function showError(message) {
    $('.message_success').hide();
    $('.message_error').hide().            // jQuery chaining keeps things tidy
      html('<div>' + message + '</div>').
      fadeIn();
  }

  // the function that shows success messages
  function showSuccess(message) {
    $('div.message_error').hide();
    $('div.message_success').fadeIn().
      .html('<div>' + message '</div>');
  }

  // this method is called when the "resend" link is clicked
  function handleResendClicked(evt) {
    evt.preventDefault();

    // send another Ajax request to the script that handles resending, using
    // the form values as parameters
    $.get( './resend_activation.php',
      $('#jq_login').serialize(),
      handleResendResponse // again we've defined this function elsewhere
    );
  }

  // called when the Ajax request above gets a response
  function handleResendResponse(data) {
    // of course you can do whatever you want with `data` here
    alert('resend request responded with: ' + data);
  }

  // called from handleLoginResponse when the login is successful
  function redirectToLoggedInPage() {
    window.location = './producer.php';
  }

  // finally, our document.ready call
  $(function() {
    // pass the names of the functions defined above to the jQuery
    // event handlers
    $("#jq_login").submit(handleLogin);
    $("#resend").live('click', handleResendClicked);
  });
}());

Of course, you won't always code like this--sometimes it really is best to just define an anonymous function() { ... } on the spot--but when things are getting nested three-levels deep this is a good way to untangle things and tends to make the way forward more clear.

(†) Anonymous closures for limiting scope


Could the server simply append the confirmation link with the returned json?

      $('div.message_error').html(
        "<div>Your account has not been activated. Please check your "  + 
        "email and follow the link to activate your account. Or click " +
        "<a href='" + data.activation_url + "' id='resend'>here</a> to re-send the link.</div>"
      );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜