3

I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.

function.php

function generateCode() {
//code here
}

function generateResult() {
//code here
}

How can I catch the function result using jQuery AJAX? I don't want to change function.php structure because it related to another pages.

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

Community
  • 1
  • 1
n00bi3
  • 75
  • 1
  • 1
  • 7
  • Can you show your ajax code, How you calling the php file? – Naresh Nov 11 '10 at 08:21
  • Are you asking how to call a PHP function within a .php file? There isn't a way to have a PHP file and then ajax call any random function in the file. It will involve calling the php file with a querystring (or post data), and then parsing that to call the correct function. – Prescott Nov 11 '10 at 08:25
  • yeaah... i've found that's impossible to do without passing variable.. Thank you :) – n00bi3 Nov 13 '10 at 13:51

3 Answers3

37

You cannot call a function in a PHP file from Javascript, full stop. The client (here: Javascript) can only communicate with the server (here: PHP) through the HTTP protocol. The HTTP protocol has no notion of files, functions or programming languages. This means you're limited to transmitting information via the URL or HTTP headers. As such, you can never call a PHP function from Javascript, all you can do is request a URL which returns data.

So, by requesting a URL, say http://example.com/myscript.php, the script myscript.php gets invoked. This script now has to figure out what it should do and output some response. This script can actually call PHP functions, e.g.:

// myscript.php

include 'functions.php'
echo generateCode();

As such, whenever you request the URL http://exmaple.com/myscript.php, you will get the output of the function generateCode(). You may notice that this works the same as when you visit a URL with a web browser. That's because this is the only mechanism to run code through a web server using the HTTP protocol and hence the only way Javascript can "call PHP functions". Javascript has no secret backdoor to call PHP functions directly.

Hope this helps.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • I thought there's a way to do that thing. I've read about JSON RPC but I don't know how to implement it. http://plugins.jquery.com/project/jsonRPC2 – n00bi3 Nov 11 '10 at 08:34
  • 2
    @n00b To use that you need a server that offers RPC services, i.e. some service, sometimes running on top of HTTP, that accepts requests and returns data. Same concepts, slightly different details. You can't simply reach into any machine over the net and invoke arbitrary functions. Thank god, because that'd be a security nightmare. – deceze Nov 11 '10 at 08:38
  • hmmm... ok then... I think answer by Battal (on below) is the answer, I'll try to implement it together with jQuery hope there's no conflict. Thank you :) – n00bi3 Nov 11 '10 at 09:22
  • @n00b Just to be clear: xajax uses the same concepts, it just gives you a framework to create an RPC-like service. Nothing you can't do yourself, and possibly overkill if you don't need to call dozens or hundreds of functions remotely. – deceze Nov 11 '10 at 09:49
  • 2
    This really should be the answer! – ragebunny May 01 '13 at 14:28
  • I saw another answer to a similar question on here (lost track of it). Anyway, the gist of it was to simply pass a 'switcher var;' meaning that, any variable in the AJAX data attribute that, when received by PHP would be used in a switch() to determine which function within the file to call. This would alleviate having to keep different functions that you wish to call from JS in separate URLs. – CodeFinity Apr 18 '15 at 13:21
  • 1
    @Vis Sure, you can use any number of patterns on top of AJAX calls. Technically you can argue that with the different parameter those are *different URLs*... In large projects you'd rather use a router and a very different file structure instead... It doesn't change anything about the basic mechanism though. – deceze Apr 18 '15 at 13:28
9

What I do is in JavaScript I pass PHP function name which I want to call. Like..

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

Here in data field "call" variable have function name to call from "function.php" file.

in "function.php" I place below code to call the function

if($_SERVER['REQUEST_METHOD']=="GET") {
$function = $_GET['call'];
if(function_exists($function)) {        
    call_user_func($function);
} else {
    echo 'Function Not Exists!!';
}
}
Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
Naresh
  • 785
  • 1
  • 11
  • 23
  • 2
    In this naïve form this is a terrible idea. `call=getAllDatabaseRecords`, `call=logInUser`... – deceze Nov 11 '10 at 08:46
  • I don't want to change the structure of my function.php, because it related to many pages. Thank you :) – n00bi3 Nov 11 '10 at 09:19
  • 1
    If you can't edit that file than make new file. Place my php code in new file and include function file in new file. Call this new file by ajax. – Naresh Nov 12 '10 at 05:17
3

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'll get php function result in msg from $.ajax success state.

kst
  • 1,498
  • 3
  • 19
  • 34