tags:

views:

39

answers:

1

I am trying to make condition to call chain function in Jquery. I used $.ajax in Jquery submit function to get values from login.php and I am trying to call fadeOut function to close login form. If login succes form will close then there will be some Success message and then it wil lalso close. And if error then form will remain and also error message. I made it also but in my login.js when I call $('.loginform').fadeOut(1000) it works also if login succes or not.

jQuery('#login').live('submit',function(event) {

$.ajax({
    url: 'lib/login.php',
    type: 'POST',
    dataType: 'json',
    data: $('#login').serialize(),
    success: function( data ) {

       for(var id in data) {
            jQuery('.' + id).html(data[id]);    
        }
$('.loginform').hide(1000);     

    }
 });

return false;
 }

});

and my login.php file includes

if(result==1){
  $arr = array ( "loginOK" => "Success." ); 

} else {

 $arr = array ( "errors" => "Please try again ." );

}
echo json_encode( $arr );

this is index.html

    <!--Login Form tag -->

<div class='errors'></div>

 <div class='loginOK'></div>

<div class='loginform'>

  <form  action ="" method="post" id="login">
    <fieldset class="loginfield">
        <legend>Login</legend>
        <div>
            <label for="username">User Name</label> <input type="text" id="username" name="username">
        </div>
        <div>
            <label for="password">Password</label> <input type="password" id="password" name="password">
        </div>
    </fieldset>
      <button type="submit" id="submit-go" ></button>
<a href="#?w=500" rel="popup_name" class="poplight">Sing up</a>

</form>

</div>
+2  A: 

the success: function( data ) { handler executes when the request is successful, not when the login is successful. You need to provide a flag in your json to indicate that, and check that flag it in your handler:

success: function( data ) {

    if(data.success) {
       for(var id in data) {
           jQuery('.' + id).html(data[id]);    
       }
       $('.loginform').hide(1000);   

    }  else {
       alert('Error logging in');
    }

}

EDIT:

Your current json object is like

{
  id_1:'html_1',
  id_2:'html_2'
}

You should make it something like

{
  html: {
    id_1: 'html_1',
    id_2: 'html_2'
  },
  success: $login_success
}
aularon
this flag must be in $.ajax ?
Meko
No, the flag is return in the json object from your page. you do the check in your serverside, and return the success flag along with the json object. Yes the above handler is your `$.ajax` `success` handler, it had a type before and it showed as `function.success: function( data ) {` but now I fixed it removing the `function.` part.
aularon
is json object will be like $flag= true ; and in jqury if (flag){$('.loginform').hide(1000);}else{alert('Error logging in');} ???
Meko
I edited the answer, check it.
aularon