Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a php function from ajax?

Tags:

ajax

php

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.

like image 741
Josip Gòdly Zirdum Avatar asked Sep 06 '16 06:09

Josip Gòdly Zirdum


People also ask

Can AJAX call a PHP function?

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

How do I run a function continuously in PHP?

React PHP is a widely used event loop for PHP. define("INTERVAL", 5 ); // 5 seconds function runIt() { // Your function to run every 5 seconds echo "something\n"; } function checkForStopFlag() { // completely optional // Logic to check for a program-exit flag // Could be via socket or file etc. // Return TRUE to stop.


2 Answers

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'));
}     
like image 61
Nitheesh K P Avatar answered Oct 21 '22 15:10

Nitheesh K P


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>
like image 34
Vishnu Bhadoriya Avatar answered Oct 21 '22 13:10

Vishnu Bhadoriya