Asked 3 years ago
17 Jun 2021
Views 490
Ardith

Ardith posted

How to call a php function from ajax?

How to call a php function from ajax?
hanuman

hanuman
answered Apr 28 '23 00:00

To call a PHP function from AJAX, you can create an AJAX request that sends data to a PHP file containing the function you want to call. Here's an example:

Create a button or other trigger in your HTML file that calls a JavaScript function when clicked:


<button onclick="callFunction()">Call PHP function</button>

Create a JavaScript function that makes the AJAX request and sends the necessary data:


function callFunction() {
  // Set up AJAX request
  $.ajax({
    url: 'functions.php',
    type: 'POST',
    data: { functionName: 'processData', arguments: [arg1, arg2] },
    success: function(response) {
      console.log(response);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log(textStatus, errorThrown);
    }
  });
}

In this example, we're sending a POST request to a file called "functions.php" and passing two pieces of data: the name of the function we want to call ("processData") and an array of arguments we want to pass to the function.

In the PHP file, check if the "functionName" parameter is set in the $_POST array, and if it is, call the corresponding function with the passed arguments:


if (isset($_POST['functionName'])) {
  $functionName = $_POST['functionName'];
  $arguments = $_POST['arguments'];

  if (function_exists($functionName)) {
    $result = call_user_func_array($functionName, $arguments);
    echo $result;
  } else {
    echo 'Function not found.';
  }
}

In this example, we're checking if the "functionName" parameter is set in the $_POST array, and if it is, we call the corresponding function using the call_user_func_array function. We then echo the result of the function back to the browser.

Post Answer