16

I have a php file func.php where I defined many functions let's say :

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

I want to call the function func1 using ajax. thank you for your help

3
  • What have you tried? What is the error you are getting? At first glance I would say that you should pass some value in using AJAX and then your PHP script will pick that value up and run the desired function using say....a switch statement. Commented Oct 18, 2013 at 19:29
  • Do all the functions accept one parameter? Commented Oct 18, 2013 at 19:33
  • @geomagas ,no I have functions with more than one parameter Commented Oct 18, 2013 at 19:38

4 Answers 4

40

You can't call a PHP function directly from an AJAX call, but you can do this:

PHP:

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

    if (isset($_POST['callFunc1'])) {
        echo func1($_POST['callFunc1']);
    }
?>

JS:

$.ajax({
    url: 'myFunctions.php',
    type: 'post',
    data: { "callFunc1": "1"},
    success: function(response) { alert(response); }
});
Sign up to request clarification or add additional context in comments.

Comments

8

You should call your php script through an ajax request, using jQuery like:

Javascript:

$.ajax({
  url: "script.php",
  data: { param1: "value1", param2: "value2" },
  type: "GET",
  context: document.body
}).done(function() {
  // your code goes here
});

You could give your parameters through data property of ajax object.

Php

// you can do isset check before 
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];

// validate // sanitize // save to db // blah blah // do something with params

More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/

1 Comment

Well, this sends parameters to the PHP script, but how do you feed them into the PHP function in that script?
1

It's a bit more complicated, but I will try to shrink it down to the basics.

You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:

  1. The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.

  2. The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.

Add the following code along with your functions:

if(isset($_GET['func']))
  {
  $func=$_GET['func'];
  if(function_exists($func))
    {
    $args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
    $result=call_user_func_array($func,$args);
    }
  else
    $result=array('error'=>"Unknown Function $func!");
  }
else
  $result=array('error'=>"No function name provided!");
echo json_encode($result);

However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.

Your example function, for instance, should look something like this:

function func1(){
    $data=func_get_args();
    if(count($data)) // at least one -- rest will be ignored
      return $data[0]+1;
    else
      return array('error'=>__FUNCTION__."() expects an argument!");
}

Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.

Comments

1

Yes you can !

here my code :

     $.ajax({
        type: "POST",
        url: "ajax.php",
        data: { kode: $(this).val(), func: 'my_func' },

        success: function(response) {
            //any success method here
        }
    });

and here the code in php to receive what function to call.

$post = (object) $_POST;
if(!$post)
    return false;

$func = $post->func;
return $func($post);

function my_func($post) {    

    $json['any_data'] = false;

    if($post->kode == 'ND'){               
        $json['any_data'] = 'ND-'.date('Y');
    }

    echo json_encode($json);

}

Hope it help you out bro... :D

Comments

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.