[php] using jquery $.ajax to call a PHP function

This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript.

<?php 
if(isset($_POST['something'] {
    //do something
}
?>

to this

<?php
function test() {
    if(isset($_POST['something'] {
         //do something. 
    }
}
?>

How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed.

This question is related to php jquery ajax

The answer is


You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).

If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:

function test() {
    // function code
}

test();

Or, use a PHP include:

include 'functions.php'; // functions.php has the test function
test();

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.


This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.


You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net

Phery::instance()->set(array(
   'phpfunction' => function($data){
      /* Do your thing */
      return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
   }
))->process();

The javascript would be simple as

phery.remote('phpfunction');

You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):

function mcrypt(variable, content, key){
  phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}

//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');

and in the server

Phery::instance()->set(array(
  'mcrypt_encrypt' => function($data){
     $r = new PheryResponse;

     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
     return $r->set_var($data['variable'], $encrypted);
     // or call a callback with the data, $r->call($data['callback'], $encrypted);
  }
))->process();

Now the variable will have the encrypted data.


I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php

After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.

For ease of use reference the function in a simple manner:

    var P = $.fn.php;

Then initialize the plugin:

P('init', 
{
    // The path to our function request handler is absolutely required
    'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',

    // Synchronous requests are required for method chaining functionality
    'async': false,

    // List any user defined functions in the manner prescribed here
            // There must be user defined functions with these same names in your PHP
    'userFunctions': {

        languageFunctions: 'someFunc1 someFunc2'
    }
});             

And now some usage scenarios:

// Suspend callback mode so we don't work with the DOM
P.callback(false);

// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Demonstrating PHP function chaining:

var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );

Demonstrating sending a JSON block of PHP pseudo-code:

var data1 = 
        P.block({
    $str: "Let's use PHP's file_get_contents()!",
    $opts: 
    [
        {
            http: {
                method: "GET",
                header: "Accept-language: en\r\n" +
                        "Cookie: foo=bar\r\n"
            }
        }
    ],
    $context: 
    {
        stream_context_create: ['$opts']
    },
    $contents: 
    {
        file_get_contents: ['http://www.github.com/', false, '$context']
    },
    $html: 
    {
        htmlentities: ['$contents']
    }
}).data();
    console.log( data1 );

The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.


You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.

Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios