Skip to content Skip to sidebar Skip to footer

Call Any PHP Function Using A Javascript AJAX Post Request

I've searched around a lot of topics, but couldn't find the answer. My goal is to have a HTML hyperlink calling a Javascript AJAX post request on a PHP page to run a PHP function (

Solution 1:

The PHP Manual states that the $_POST super global variable only contains the post arguments for post data of type application/x-www-form-urlencoded or multipart/form-data.

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

However, you are trying to send a post request with the body of type application/json.

To read a raw body in PHP you can do this:

$postdata = file_get_contents("php://input");

This will give you a string of the entire request body. You can then json_decode this string to get the desired JSON object.

As for the part of calling a function supplied in the request, the call_user_func_array will do the job fine. Whether or not that is something you should do is an entirely separate issue. From what I understand, you are edging on on the concept of a router and a controller.

I have writen a simple snippet of what I think you want to do:

<?php

switch ($_SERVER['REQUEST_METHOD']) {
  case 'POST':
    post_handler();
    return;
  case 'GET':
    get_handler();
    return;
  default:
    echo 'Not implemented';
    return;
}

function post_handler() {
  $raw_data = file_get_contents("php://input");
  $req_body = json_decode($raw_data, TRUE);
  call_user_func_array($req_body['function'], $req_body['args']);
}

function get_handler() {
  echo 'This page left intentionally blank.';
}

function some_function($arg1, $arg2) {
  echo $arg1.' '.$arg2;
}

?>

Solution 2:

Comment json_decode and output your $_POST by calling print_r ($_POST); you should see your data structure, if it is a simple array with data keys and values then you don't have to decode it but if the array have a single column and it's value is your data then take it's key and use it to decode the content


Post a Comment for "Call Any PHP Function Using A Javascript AJAX Post Request"