Home > Backend Development > PHP Problem > How to call php function from js

How to call php function from js

Release: 2023-02-28 08:44:01
Original
7800 people have browsed it

How to call php function from js

JS method of calling php function:

jQuery.ajax({
    type: "POST",
    url: 'your_functions_address.php',
    dataType: 'json',
    data: {functionname: 'add', arguments: [1, 2]},
    success: function (obj, textstatus) {
                  if( !('error' in obj) ) {
                      yourVariable = obj.result;
                  }
                  else {
                      console.log(obj.error);
                  }
            }});
Copy after login

Your _function_address.php is as follows:

 <?php
    header(&#39;Content-Type: application/json&#39;);

    $aResult = array();

    if( !isset($_POST[&#39;functionname&#39;]) ) { $aResult[&#39;error&#39;] = &#39;No function name!&#39;; }

    if( !isset($_POST[&#39;arguments&#39;]) ) { $aResult[&#39;error&#39;] = &#39;No function arguments!&#39;; }

    if( !isset($aResult[&#39;error&#39;]) ) {

        switch($_POST[&#39;functionname&#39;]) {
            case &#39;add&#39;:
               if( !is_array($_POST[&#39;arguments&#39;]) || (count($_POST[&#39;arguments&#39;]) < 2) ) {
                   $aResult[&#39;error&#39;] = &#39;Error in arguments!&#39;;
               }
               else {
                   $aResult[&#39;result&#39;] = add(floatval($_POST[&#39;arguments&#39;][0]), floatval($_POST[&#39;arguments&#39;][1]));
               }
               break;

            default:
               $aResult[&#39;error&#39;] = &#39;Not found function &#39;.$_POST[&#39;functionname&#39;].&#39;!&#39;;
               break;
        }

    }

    echo json_encode($aResult);?>
Copy after login

Recommended: phpserver

The above is the detailed content of How to call php function from js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template