Patrioticcow
Patrioticcow

Reputation: 27048

How to call multiple PHP functions through ajax, best practices?

I have some ajax calls in multiple JavaScript functions. Each one does a post / get to a functions.php file

The functions.php has multiple functions that should correspond with the ones from JavaScript.

For example in js I have:

function one() {
$.ajax({ 
    type: 'POST', 
    url: 'http://www.example.com/functions.php', 
    data: vals,
    dataType:'json',
    success: function (data) {
        alert(data);
    }
});
}

function two() {
$.ajax({ 
    type: 'POST', 
    url: 'http://www.example.com/functions.php', 
    data: othervals,
    dataType:'json',
    success: function (data) {
        alert(data);
    }
});
}

function three() {
$.ajax({ 
    type: 'GET', 
    url: 'http://www.example.com/functions.php',  
    data: { get_param: 'user' },
    dataType:'json',
    success: function (data) { 
        alert(data);
    }
        
});
}

In PHP I have something like this:

if (isset($_POST['city'])) {  // this comes from the javascript vals json object
$city = $_POST['city'];
   function one() {
    // do something

    return true;
   }
}

function two() {
 // do something
 return true;
}


if (isset($_GET['get_param']) && $_GET['get_param'] == 'user'){
function three() {
 // do something
return true;
}
}

Maybe the PHP side is a bit confusing the way I write it, but in the end I want the function one to only deal with the corespondent function from the PHP file. Obviously they don't need to have the same name.

The PHP functions can return true or false or 1 or 0, and that suppose to be the alerted data alert(data);.

If there is more confusion on what I want please let me know and I'll clarify.

Upvotes: 1

Views: 2897

Answers (2)

ThePrimeagen
ThePrimeagen

Reputation: 4582

Have you checked out a REST library style. It looks like your doing basically that but a bit more confusing. When i say REST library i do not mean a purely RESTful library, but instead each function in your back-end is navigable via url.

The way your doing it is fine (as long as the functions data does not depend on any other function data (as it could lead to some funny results)). Its just a lot easier to do more of a restful approach. Its fairly simple to set up a rest library.

I just find that doing the whole $_POST[...] and then keep doing it is just cumbersome over time and becomes harder and harder to manage, because there is always some new twist on what is needed then you end up with 100's of methods for taking care of calling back end functions.

MyApi = {    
    /**
     * The API Version
     */
    API_VERSION: "0.5",
    SITE_URL: "http//myurl.com/",
    /**
     * The API URL
     */
    apiURL: function(tokens) {
        return MyApi.SITE_URL + MyApi.API_VERSION + "/api/" + MyApi.apiTokenizer(tokens);
    },
    /**
     * The tokenizer for the API.
     */
    apiTokenizer: function(tokens) {
        var str = '';
        $.each(tokens, function(key, value) {
            str += value + "/";
        })
        return str;
    }
}

Thats the javascript for producing new api links, then you could have something like

function callBackend(tokens) {
    $.ajax({ 
        type: 'POST', 
        url: MyLibrary.apiURL(tokens),
        dataType:'json',
        success: function (data) {
            alert(data);
        }
    });
}

On your backend you would need an .htaccess file like so

RewriteRule 0\.5/(.*) api/_MyApi.php?v=0\.5&state=$1 [QSA]

Then you could write a back end switch statement that would take apart the state (delimiters would be "/") that would navigate you to the end time library call.

<?php
    $state = MyParser::Parse($_REQUEST["state"]);
    $output = array();
    switch ($state) {
        case "case1":
            //do stuff
            break;
    }

    echo json_encode($output);
?>

That way output is always handled the same way.


Just as a note. That was a very VERY simple and INCOMPLETE implementation, but i find that its a lot easier to maintain than a $_POST that goes to 1 of 100 different files that all have very similar output and all of that.

Cheers! Happy coding

Upvotes: 0

Michiel Overeem
Michiel Overeem

Reputation: 3982

Why not split the PHP functions in separate smaller scripts? They stand for different endpoints in your application and cannot be called together, so they should not be together.

Upvotes: 1

Related Questions