简体   繁体   中英

Javascript scope and Ajax call doesn't work correctly

I have some problems.

First of all, my php file shoutbox.php, it's used for to log in an user.

session_start();

if(! isset($_SESSION["loggedIn"])) {

 include "login.html";

}

else {

    if(isset($_POST["submit"]) && $_POST["submit"] == "Log In") {

        if(! isset($_POST["username"]) || $_POST["username"] == "" || ! isset($_POST["password"]) ||  $_POST["password"] == "")  {

            $GLOBALS["logErr"] = "Please, filln all fields!";

            echo json_encode(false);
        }

        else if(isset($_POST["username"]) && $_POST["username"] != "" && isset($_POST["password"]) && $_POST["password"] != "") {

            if(isset($_POST["select"]) && $_POST["select"] != "") {

                session_start();

                $_SESSION["loggedIn"] = TRUE;
                $_SESSION["username"] =  $_POST["username"];
                $_SESSION["password"] = $_POST["password"];
                $_SESSION["type"] = $_POST["select"];
                $_SESSION["ip"] = get_ip_address(); /* Return current ip */

                $user = array(
                              "username" => $_SESSION["username"],
                              "islogged" => $_SESSION["loggedIn"],
                              "password" => $_SESSION["password"],
                              "ip" =>  $_SESSION["ip"],
                              "type" =>  $_SESSION["type"]
                              );

                echo json_encode($user); 

            }
        }
    }

    else if(isset($_POST["logout"]) && $_POST["logout"] == "Log Out") {

        session_start();

        unset($_SESSION["loggedIn"]);
        unset($_SESSION["username"]);
        unset($_SESSION["password"]);
        unset($_SESSION["type"]);
        unset($_SESSION["ip"]);

        echo json_encode(false);
    }

    if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"] == TRUE) {

  echo json_encode(true); /* user is logged in */



    }

  else {

        echo json_encode(false); /* user is not logged in */

  }

}

It returns false or true and if is true it returns user array encoded.

This is the Ajax call, I have to call 2 responses, false or true and if response is true, also user array..

function sb_UserIsLoggedIn() {
                              $.ajax({
                                  url: 'shoutbox.php',
                                  type: 'POST',
                                  dataType: 'json',

                                  success: function(response, user) {

                                    if(response) {

                                             function user(user) {                                             

                                      CurrUserInfo = {
                                          u_name: user["username"],
                                          u_psw: user["password"],
                                          ip: user["ip"],
                                          typelog: user["type"],
                                          logged: user["islogged"]
                                      };

                                      if(CurrUserInfo.typelog == "anonimous") {
                                          OnlineListObj.onlineList.anonimous.push(user["username"]);
                                      }
                                      else if(CurrUserInfo.typelog == "visible") {
                                          OnlineListObj.onlineList.visible.push(user["username"]);
                                      }

                                      OnlineListObj["onlineList"]["total"] = OnlineListObj.onlineList.anonimous.length + OnlineListObj.onlineList.visible.length;

                                      OnlineListObj["onlineList"]["phrase"] = lang["there_are"] + OnlineListObj.onlineList.total  + lang["online"] + OnlineListObj.onlineList.anonimous.length + lang["anonimous"] + OnlineListObj.onlineList.visible + lang["visibles"];

                                         LoggedIn = true;

                                      window.alert(LoggedIn);
                                      window.alert(OnlineListObj["onlineList"]["total"]);
                                      window.alert(OnlineListObj["onlineList"]["phrase"]);
                                      window.alert(CurrUserInfo.ip);
                                      window.alert(CurrUserInfo.typelog);
                                      window.alert(CurrUserInfo.logged);
                                      window.alert(CurrUserInfo.u_name);
                                      window.alert(CurrUserInfo.u_psw);


                                    }

                                  }

                                    else {

                                      window.location.href = "shoutbox.php";
                                    }

                                  },

                                  error: function(response) {
                                      sb_Error("Unknown error, try again");
                                      console.log(lang["ajax_error"]);
                                      console.log(response.responseText);


                                      LoggedIn = false;
                                  },
                              });
                          }

Alerts say undefined for these:

 window.alert(CurrUserInfo.ip);


   window.alert(CurrUserInfo.typelog);
                                      window.alert(CurrUserInfo.logged);
                                      window.alert(CurrUserInfo.u_name);
                                      window.alert(CurrUserInfo.u_psw);

This because the call to user array fails...but a call works correctly, it returns true or false.. Why does it work and the other (to user array) not? I'd like ajax call true or false and user array.

Other problem:

In code about sb_isUserLoggedIn() I defined a var, LoggedIn...

But if you call LoggedIn in another function, returns undefined:

 /* Checks if the user is online */

                function sb_isOn() {

                  sb_UserIsLoggedIn();

                    if(LoggedIn != false) {

                         return true;

                    } 

                    else {

                         return false;

                    }

              }  

As I written, this code returns an error, LoggedIn is undefined.

How can I resolve all these problems?

Thanks in advance.

It looks to me that the PHP makes two calls to echo json_encode() when it is successful. One to echo the user array and one to echo true . I think that results in invalid JSON.

I suggest you write the PHP so it makes one and ONLY one call to echo json_encode() . You could have it return the following for success:

echo json_encode(array("success" => true, "user" => $user));

And the following for failure:

echo json_encode(array("success" => false, "message" => 'Please, fill in all fields!'));

Then in the Javacript, you can have something like the following:

success: function(result) {
    if (result.success) {
        var user = result.user;
        // Do something with user here.
    } else {
        var message = result.message;
        // Do something with message here.
    }
}

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