'How to call a php function from ajax?

I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?

Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.



Solution 1:[1]

You cannot call a PHP function directly from an AJAX request, but you can do this instead:

<? php 
    function test($data){
        return $data+1;
    }

    if (isset($_POST['callFunc1'])) {
        echo test($_POST['callFunc1']);
    }
?>
<script>
    $.ajax({
        url: 'myFunctions.php',
        type: 'post',
        data: { "callFunc1": "1"},
        success: function(response) { console.log(response); }
    });
</script>

Solution 2:[2]

As a structure for this kind of purposes, I suggest this:

PHP

<?php
    if(isset($_POST['action'])){
        if ($_POST['action'] == "function1") { func1(); }
        if ($_POST['action'] == "function2") { func2(); }
        if ($_POST['action'] == "function3") { func3(); }
        if ($_POST['action'] == "function4") { func4(); }
    }

    function func1(){
        //Do something here
        echo 'test';
    }
?>

jQuery

var data = { action: 'function1' };

$.post(ajaxUrl, data, function(response) {
    if(response != "") {
        $('#SomeElement').html(response);
    }else{
        alert('Error, Please try again.');
    }
});

As mentioned, you can't call a PHP function directly from an AJAX call.

Solution 3:[3]

If I understand correctly, yes you can. Put all your functions in one php file and have the ajax pass as a parameter which one you want to call. Then with a switch or if structure, execute the one you want.

Solution 4:[4]

jquery:

$(document).ready(function(){
    $('#tfa_1117700').change(function(){
        var inputValue = $(this).val();
        var v_token = "{{csrf_token()}}";
        $.post(
            "{{url('/each-child')}}",
            { dropdownValue: inputValue,_token:v_token },
            function(data){
                console.log(data);
                $('#each-child-html').html(data);
            }
        );
    });
});

php:

public function EachChild(Request $request)
{
    $html ="";
    for ($i=1; $i <= $request->dropdownValue; $i++)
    { 
        $html = $i;
    }
    echo $html;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 isherwood
Solution 3 iliaz
Solution 4 Asef Hossini