简体   繁体   中英

Calling a JS function from PHP

I'm making a site with several calls to PHP via AJAX, right now AJAX uses POST to get a echoed string from PHP and then compares that in a switch and then does what is required. Example in the code below

function submitPHP(dataForPHP){
    //Runs ajax request
    $.ajax({
        type : "POST",
        url : 'initPHP.php',
        dataType : 'text',
        data : dataForPHP,
        success : function(data){
            //Checks echoed data from PHP
            switch(data){
                case "LOGIN_ACCEPTED":
                    loggedInFunction();
                    break;
                case "LOGIN_FAILED":
                    loggedInFailedFunction();
                    break;
            }
        }
    });
}

I'm thinking if there is a way for the PHP to return what function (like "loggedInFunction();") I want to call instead of a string that I then have to compare and then call the function? I can change the AJAX to use JSON instead if that does it.

I've been looking around on other similar questions here on stack on most of them want to echo a whole function which is not what I want to do.

Thanks in advance!

I'd do this.

  1. use HTTPS to perform login, HTTP really is insecure nowadays;
  2. create a controller object with all allowed methods ( actions );
  3. call an action of that controller .

The idea of having a controller is convenient on several levels:

  • security: if a method is not in the controller you cannot call it, so it is a way to know what can be called and what is absolutely not possible to call;
  • cohesion: the methods are all next to each other and easier to maintain;
  • encapsulation: if there is any state it can be held easily inside the context of that object.

This is an example:

loginController = {
  "acceptAction": function () {
  },
  "failAction": function () {
  }
};

You can now call those methods from the AJAX handler. Say the server tells you what you must do. A verb so to speak, such as accept or fail . You can then do:

"success": function (data) {
  loginController[data + "Action"]();
}

And that's it.

BTW: this is just the very basic MVC pattern. Oldie but goldie :)

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