1

After the client presses a button - a server side function must be executed and according the result different client side functions be executed..

To achive this I used AJAX and wrote this function :

function invoke_php(file_name, parameters){     
   parameters = typeof parameters !== 'undefined' ? parameters : '';
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {             
           switch (xmlhttp.responseText) {
             case "func1":
                func1();
             break;
             case "func2":
                func2();
             break;
             default:
                default_func();
           } 
       }
   };
   xmlhttp.open("POST", file_name+"?"+parameters, true);
   xmlhttp.send();
}

Server side functionality is performed in separate php file, which returns the name of the function to run. the invoke_php function uses switch on the respone text and execute the suitable client-side function...

It feels like there is a better way to do this.... Any improvement suggestion will be appreciated..:)

1 Answer 1

1

I would recommend you to:

  1. remove the switch case (which is usually not efficient and tend to become very verbose)
  2. pass the full URL to the function
  3. pass the list of callbacks to the function, in that way you won't rely on global definition of callbacks

Here is what the code could look like:

function invoke_php(url, callbacks){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && callbacks) {
            var fn = callbacks[xmlhttp.responseText] || callbacks._default || function () {};
            fn();
        }
    };
    xmlhttp.open("POST", url, true);
    xmlhttp.send();
}

invoke_php(
    'test.php?myparams=true',
    {
        _default: function () {},
        func1: function () {
            console.log('func1');
        },
        func2: function () {
            console.log('func2');
        },
    }
);

Let me know if this helps.

Thanks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.