JavaScript and PHP Functions

How can I call PHP functions by JavaScript?

Yes, you can do ajax request to server with your data in request parameters, like this (very simple):

Note that the following code uses jQuery

jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},

success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});

and your_functions_address.php like this:

    <?php
header('Content-Type: application/json');

$aResult = array();

if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }

if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }

if( !isset($aResult['error']) ) {

switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;

default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}

}

echo json_encode($aResult);

?>

Javascript and PHP functions

You can not call a PHP function from Javascript...

Javascript is a client language (it's executed on the Web browser, after receiving the web page) while PHP is on the server side (it's executed before the web page is rendered). You have no way to make one call another.

...but you can get the result of an external PHP script

There is a Javascript function called xhttprequest that allows you to call any script on the Web server and get its answer. So to solve your problem, you can create a PHP script that outputs some text (or XML, or JSON), then call it, and you analyze the answer with Javascript.

This process is what we call AJAX, and it's far easier to do it with a good tool than yourself. Have a look to JQuery, it's powerful yet easy to use Javascript library that has built-in AJAX helpers.

An example with JQuery (client side) :

$.ajax({
type: "POST", // the request type. You most likely going to use POST
url: "your_php_script.php", // the script path on the server side
data: "name=John&location=Boston", // here you put you http param you want to be able to retrieve in $_POST
success: function(msg) {
alert( "Data Saved: " + msg ); // what you do once the request is completed
}

Calling PHP Function within Javascript

The PHP function cannot be called in the way that you have illustrated above. However you can call a PHP script using AJAX, code is as shown below. Also you can find a simple example here. Let me know if you need further clarification

Using Jquery

<script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
function compute() {
var params="session=123";
$.post('myphpscript.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
}
</script>

Barebones Javascript Alternative

   <script type="text/javascript">

function compute() {
var params="session=123"
var xmlHttp;
var addend_1=document.getElementById("par_1").value;
var addend_2=document.getElementById("par_2").value;

try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("No Ajax for YOU!");
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
}
xmlHttp.open("POST", "http://yoururl/getjs.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>

How to call a JavaScript function from PHP?

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.

All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".

There are many ways to do this, but here are a couple.

Using just PHP:

echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;

Escaping from php mode to direct output mode:

<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>

You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.

Here's an example of what I think you're doing with jQuery's AJAX

$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;

// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();

// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);

function someOtherFunctionYouWantToCall() {
// stuff
}

Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.

$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);

* Or JSON or XML etc.

Call php function from JavaScript

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

Plain Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

The javascript

// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}

The HTML

<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>

The PHP

// file myAjax.php
<?php
echo 'hello world!';
?>

Try it out: http://jsfiddle.net/GRMule/m8CTk/


With a javascript library (jQuery et al)

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}

Try it out: http://jsfiddle.net/GRMule/WQXXT/

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

If this is all you need to do, write the plain javascript once and you're done.

Documentation

  • AJAX on MDN - https://developer.mozilla.org/en/ajax
  • XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
  • XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
  • jQuery - http://jquery.com/download/
  • jQuery.ajax - http://api.jquery.com/jQuery.ajax/


Related Topics



Leave a reply



Submit