Home  >  Article  >  Backend Development  >  How to call php function from js

How to call php function from js

尚
Original
2019-10-31 16:39:587652browse

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);
                  }
            }});

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);?>

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!

Statement:
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
Previous article:Is php simpler than java?Next article:Is php simpler than java?