Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call php function with arguments using Jquery

Tags:

jquery

ajax

php

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

like image 580
Tarik Mokafih Avatar asked Oct 18 '13 19:10

Tarik Mokafih


People also ask

Can I call PHP function from jQuery?

Also, apart from doing this with the click of a button, a PHP function can be called using Ajax, JavaScript, and JQuery.

How to call php function in jQuery ajax?

What you want is something like: $. ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', success: function(output) { alert(output); } });

Can Javascript call PHP function?

You can call PHP function through Javascript by passing the value, you need as output of PHP function as a string in Javascript.

Why use ajax?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.


1 Answers

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); }
});
like image 85
Steve Avatar answered Sep 17 '22 11:09

Steve