27

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.

5
  • yes you can. just add some flag in current url for ajax request. like your current url ?isAjax = 1 and in script check that flag Commented Sep 6, 2016 at 6:26
  • yes you can do that. You have to just take care about parameters , so that call to a function can distinguish from each other. in php you can use switch cases (not always required) based on these parameter to distinguish the function Commented Sep 6, 2016 at 6:26
  • mvc pattern would have help, another way is to call the functions based on the parameters passed in url.. iF ELSE clauses on a parameter and call the respective function Commented Sep 6, 2016 at 6:27
  • You may use the routing approach that is provided by various frameworks. For instance, slim framework Commented Sep 6, 2016 at 6:28
  • I've built a fairly large project without a backend framework, I figure I probably should have now. I think when I complete the majority of it and I have some time spare, I'll convert it across. Commented Sep 6, 2016 at 6:31

5 Answers 5

32

For AJAX request

  1. Include jQuery Library in your web page. For e.g.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    
  2. Call a function on button click

    <button type="button" onclick="create()">Click Me</button>
    
  3. While click on button, call create function in JavaScript.

    <script>
        function create () {
            $.ajax({
                url:"test.php",    //the page containing php script
                type: "post",    //request type,
                dataType: 'json',
                data: {registration: "success", name: "xyz", email: "[email protected]"},
                success:function(result){
                    console.log(result.abc);
                }
            });
        }
    </script>
    

On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in PHP and return in JSON format e.g.

$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];

if ($registration == "success"){
    // some action goes here under php
    echo json_encode(array("abc"=>'successfuly registered'));
}     
Sign up to request clarification or add additional context in comments.

1 Comment

I am confused that why he accepted your answer. He is asking to call a particular php function from ajax and you are calling a javascript function.
23

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>

1 Comment

Be careful with this approach because the response will include everything not just the result of echoing the function
8

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.

Comments

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.

Comments

0

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

1 Comment

Please try to add some more context to your answer. Ask yourself: what does this do if I didn't read the question completely/or misunderstood it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.