سؤال

EDIT: Okay, now that I think about it, JSON does sound decent for this, and as long as I code right, there shouldn't be a syntax error to disrupt it or anything.


Good evening!

Something that's always bothered me is how to handle returned data from PHP in an AJAX request, and how to even return the data!

Say I have a log in form, and it processes submitted form data through AJAX. We'll say we use GET for simplicity's sake.

"page.php?username=Foo&password=bar"

Here's what bugs/irks me, and why I feel compulsive and feel as though I need to know the right way to do this:

I sent the data and it's been processed. Now what?

Say my username and password are valid/correct. What do I do?

Return true in PHP? A string?

Then what do I do with the JavaScript?

   if(ajaxRequest.responseText=="true"){
       //Username and password are correct! Execute this...
   }

What I thought was a cool idea was returning a JSON object as a string, and parsing through JavaScript.

  var object=JSON.parse(ajaxRequest.responseText);
  if(object.success=="true"){
       //Username and password are correct! Execute this...
   }

But, what if my username and password combo is...wrong? Do I return false via PHP, or a string again?

Between true and false, there are only 2 choices: 1. The username and password were correct 2. The username and password were not correct

But what if the username doesn't even exist? Returning "false" doesn't help me tell the client exactly why they can't log in.

Diving deeper into my OCD on this, what about unexpected or parse errors?

If there is some sort of DB connection error or a parse error, how do I return that to tell the user? I looked into Trying...and Catching syntax errors, but I had no luck.

A recent thought I had was to do THIS:

If everything executes properly, and the username and password exist (going back to our original scenario), then we don't return ANYTHING. The responseText will be an empty string. That means the user logged in successfully!

Otherwise, if there is an error, DO return something (typically a string) and display it as an error.

Am I going about this the right way? Am I on the right track?

هل كانت مفيدة؟

المحلول

My personal preference, which is in no way "THE" correct way to do it, is to use JSON for everything.

So I have a JavaScript function that, when a form is submitted, will convert the form data to a JSON string and POST it to the server.

The server then processes it, and returns another JSON object. In your login example, therefore, the server would receive:

{"username":"Foo","password":"bar"}

And it would return one of these:

{"ok":false,"error":"No user with that name was found."}
{"ok":false,"error":"The password you entered was incorrect."}
{"ok":false,"error":"Failed to log you in (error code: ###)"}
{"ok":true,"redirect":"/home"}

Every AJAX request response has this "ok" property. If it is false, there will be an "error" property saying what happened (and there may be additional data depending on the situation). On success, the "ok" property is true. A lot of requests just get {"ok":true} all by itself, but sometimes there is additional data here too.

As I said, this is not "THE" way to do it, but I like it and it's consistent.

EDIT: Forgot to mention the bit about PHP errors.

The JavaScript that receives the server's response attempts to parse it as JSON using a try...catch block. If parsing fails, then there was a server error. In such a case, an error message is popped up with the raw response from the server, with a note advising the user to contact me about the error message.

نصائح أخرى

A fairly common pattern for this is to return an error array, which could be a JSON object in your case. If the error array is empty you are good to go, and if it's not then display the error to your user.

I think you are over complicating yourself with the if and buts of response.

Following is an old example i have have used once. i am using following ajax to send username/password to php file through AJAX

$.ajax({
    type: "POST",
    url: SITE_URL+"ajax_files/ajax_login.php",
    data: dataString,
    dataType: "json",
    cache: false,
    success: function(data){
        if(data.success=='y') {
            window.location.href='index.php';
        } else {
            $('#messagesnormal').hide();
            //Show results div
            $('#resultsAjax').show();
            //Put received response into result div
            //$('#resultsAjax').html(data.msg);
        }
    }
});

And following is my php file code.

header('Content-Type: application/json');
include("../config/config.php");
$username = trimdata($_POST['username']);
$password = trimdata($_POST['password']);
$r = $db->select("SELECT * FROM users where email = '".dbAddslashes($username)."' and password='".dbAddslashes($password)."' and status = '1' and locked_by_admin = '0'");
if($db->row_count > 0) {
    while ($row=$db->get_row($r, 'MYSQL_ASSOC')) {
       $_SESSION["userdata"]["userid"]  = $row['user_id'];
       $_SESSION["userdata"]["usertype"] = $row['type'];
       $_SESSION["userdata"]["useremail"] = $row['email'];
       $_SESSION["userdata"]["name"] = $row['name'];
       if($_SESSION["userdata"]["usertype"]=='1') {
            $_SESSION["userdata"]["userrole"] = 'admin';
       } else {
            $_SESSION["userdata"]["userrole"] = 'user';
       }
       $_SESSION["userdata"]["last_login"] = $row['last_login'];
       $_SESSION["userdata"]["last_login_ip"] = $row['last_login_ip'];
       $success = 'y';
       $msg = 'login successfull';

       /*Insert login time and IP*/
       $data = array('last_login' => time(), 'last_login_ip' => getRealIPAddr());
       $rows = $db->update_array('users', $data, "user_id=".$row['user_id']);

       print json_encode(array('success' => $success, 'msg' => $msg));
       exit;
    }
} else {
    $success = 'n';
    $msg = '<div class="gagalsmall">Invalid credentials.Please try again.</div>';
    print json_encode(array('success' => $success, 'msg' => $msg));
    exit;
}
exit;

Although i have only queried for both username password exists, you can apply similar check on different occasion. then pass these values back to jquery in json format.

You can use all the values assign in php as i did above on line:

if(data.success=='y') {

where success is assigned from php file.

Hope this helps you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top