Creating jQuery AJAX requests to a PHP function

I believe there’s a fundamental misunderstanding of how the technology works here.

AJAX (Javascript), Flash, or any client-sided technology cannot directly call PHP functions (or other languages running on the server).
This is true for going the other way around as well (eg: PHP can’t call JS functions).

Client and server codes reside on different machines, and they communicate through the HTTP protocol (or what have you). HTTP works roughly like this:

Client-server model

Client (eg: browser) sends a REQUEST -> Server processes request and sends a RESPONSE -> Client gets and displays and/or processes the response

You have to see these requests and responses as messages. Messages cannot call functions on a server-side language directly 1, but can furnish enough information for them to do so and get a meaningful message back from the server.

So you could have a handler that processes and dispatches these requests, like so:

// ajax_handler.php
switch ($_POST['action']) {
    case 'post_comment':
        post_comment($_POST['content']);
        break;
    case '....':
        some_function();
        break;
    default:
        output_error('invalid request');
        break;
}

Then just have your client post requests to this centralized handler with the correct parameters. Then the handler decides what functions to call on the server side, and finally it sends a response back to the client.


1 Technically there are remote procedure calls (RPCs), but these can get messy.

Leave a Comment