Make ajax call to a php function include on same page

ajax, php

Solution

Expanding on what Quentin said, You can't directly call a php function from an Ajax request but you can pass over GET & POST Data to a php script and perform an if or switch statement to call your function, so you could do something like this...

//Your Ajax Call

$.ajax(
{

      type:'GET',
      url:'functions.php',
      data:"function_to_call=0", 
      success: function(data){
        alert('successful');
}

});

And your PHP functions script would look something like this

     switch ($_GET['function_to_call']) 
     {

         case 0:
         {   
               function1();
               break;
         }

        case 1: 
        {
              function2();
              break;
        }
        default: break;

     }

//And your functions. 

    function function1() {
         echo "This is function 1";
    }
    function function2() {
         echo "This is function 2";
}

Problem

My question might sound old and already answered to you but I did not find a satisfying answer to my question. Let me explain my scenario clearly, I got index.php like this index.php ``` <?php inlcude("connect.php"); include("functions.php"); ?> <html> $(document).ready(function() { $('#button').click(function() { $.ajax({ type: 'GET', data: 'method=test', success: function(data) { alert(data); } }); }); }); </html> ``` I did not pass the URL in the ajax call and I got the data alert successfully but the entire page from `<html>` to `</html>`. When I provide the url to functions.php I get the expected output in the alert box. I hope you guyz have a close guess about my question. My question is I need to call a function from `functions.php` which is already included in my `index.php` page. I don't wanna use `functions.php` again in the ajax 'URL: ' as `functions.php` would be called twice. This is to avoid server load. Let me the you guyz come up with interesting ideas. Thank you.

Original source