PHP function call using jQuery AJAX

I read all the topics about my question, but I can not solve my problem. I want to get the result of a php function using jQuery AJAX.

function.php

function generateCode() {
//code here
}

function generateResult() {
//code here
}

How can I catch the result of a function using jQuery AJAX? I do not want to change the structure of function.php because it is linked to other pages.

Refer to using jquery $ .ajax to call a PHP function , no answer can solve my problem. Thank you.

+3
source share
4 answers

To use PHP classes and functions directly, you can use xajax .

0
source

PHP Javascript, . (: Javascript) (: PHP) HTTP-. HTTP , . , URL HTTP-. , PHP Javascript, , , URL-, .

, URL-, http://example.com/myscript.php, script myscript.php. script , - . script PHP, :

// myscript.php

include 'functions.php'
echo generateCode();

, , URL http://exmaple.com/myscript.php, generateCode(). , , URL- -. , - HTTP , , , Javascript " PHP". Javascript PHP.

, .

+33

JavaScript PHP, . ..

function MyFunction() {
jQuery.ajax({
    type: "GET",
    url: "function.php",
    data: "call=generateCode",
    success: function(response){
        //do something
    });
}

Here in the data field "call" the variable is the name of the function to call from the file "function.php".

in "function.php" I put below code to call a function

if($_SERVER['REQUEST_METHOD']=="GET") {
$function = $_GET['call'];
if(function_exists($function)) {        
    call_user_func($function);
} else {
    echo 'Function Not Exists!!';
}
}
+8
source

JQuery

$.ajax({
      url: "script.php",
      type: "POST",
      data: "id=1",
      success: function(msg){
         alert(msg);
      }
   }

Php

<?php
    $id = $_POST['id'];
    echo "The id is ".id;
?>

You will get the result of the php function in msgfrom state $.ajax success.

+3
source

Source: https://habr.com/ru/post/1774246/


All Articles