简体   繁体   中英

submitting a login form using ajax

I have this javascript in one of my forms. This one is the login form I get the URL from the form itself I'm using API style, ("not sure if I got the concept right") but I will attach the code down

var formup = $('#loginfrom');
formup.submit(function () {
    $.ajax({
        type: formup.attr('method'),
        url: formup.attr('action'),
        data: formup.serialize(),
        success: function (data) {
            alert('you have successfuly logged in');
            window.location = "profile.html";
        }
    });

    return false;
});

here is my login function called from api file

if(!mysql_fetch_array($result)){
return $res;
}
else
    return $resc;

where $res returns "error", and $resc returns "correct"

and my api.php

if(!isset($function))
        $resp['err'] = "Function: ".$action." does not exist";
    else
        $resp = $function($request);

when I enter the correct user name and password, it works fine and I'm directed to the user profile.

However, I don't know how to handle if I got the user name or password incorrect I don't want to be directed to profile

I do think the return from php should do something to tell the javascript that the login did not work then do something else

please provide me some help regarding this problem, I will appreciate it.

The request is always a success so, you have to check the value of the data variable to redirect to an error page

...
success: function (data) {
  if ( data == 'correct') {
    alert('you have successfuly logged in');
    window.location = "profile.html";
  } else {
     // handle error
  }
}
...

Change your login code to this

if(!mysql_fetch_array($result)){
  echo 'failure'; die;
}
else    {
    echo 'success'; die;
}

And change your ajax success to this

success: function (data) {
        if (data == 'success') {
            alert('you have successfuly logged in');
            window.location = "profile.html";
        } else {
             alert('Login Failed');
        }
    }

Use datatype as json to get the return value from php. Check my suggestions in the below code.

$.ajax({
        type: formup.attr('method'),
        url: formup.attr('action'),
        data: formup.serialize(),
        dataType: 'json',
        success: function (data) {

            if(data.error == 0) {
                alert('you have successfuly logged in');
                window.location = "profile.html";
            } else {

                alert("error");
            }
        }
    });

In your php file, convert $res and $resc into an array and then later use json_encode. Like this,

if(!mysql_fetch_array($result)){
    echo array('value'=>$res,'error'=>0);
}
else
    echo array('value'=>$res,'error'=>1);

You can do something with the data or you can have PHP return a 401 status, if you return something with your PHP instead of a 401 status than you can have your JavaScript check the returned text:

var formup = $('#loginfrom');
formup.submit(function () {
    $.ajax({
        type: formup.attr('method'),
        url: formup.attr('action'),
        data: formup.serialize(),
        success: function (data) {
            console.log(data);
            // check your console (press F12 in Chrome or Firefox with firebug plugin)
            // do something if the data is valid.
            window.location = "profile.html";
        }
    });

    return false;
});

When the login fails in PHP and you want to return 401 (causing your javascript success function not to be called but you might need a fail/error function in JS.

header("HTTP/1.0 401 Unauthorized");

And you need to add a fail callback in your javaScript so the user knows the log in failed:

    $.ajax({
        ...
        success: function (data) {
          ...
        },
        error: function(){
           //inform the user
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM