Javascript: Executing a PHP function; Obtaining the PHP return value

I need to use javascript to execute a php function and then obtain the value the php function returns.  This is a problem I need to solve at work.  I enter the URL of the php into the web browser and a new window appears with the value I need to save.  Also, what do I need to install to be able to develop and test a similar issue from home?  i.e. some server that allows me to use a php function that will return a value that I can extract via javascript.  Finally, I am new to javascript and php, what are to tools I need to use to develop, test and implement javascript and php???
LVL 1
DCCoolBreezeAsked:
Who is Participating?
 
Olaf DoschkeConnect With a Mentor Software DeveloperCommented:
what javascript variable will hold the data.
In the code Julian gave you initially that's "resp" as in response from this part of the code:
$.get('api/getSpecialValue.php', data, function(resp) {
      if (resp.status) {
        alert('You clicked ' + resp.message);
      }
      else {
        alert('Oops something was wrong with your request');
      }
    }

Open in new window


Here the third parameter of the get cal actually is a function. functions are objects in javascript, that you can not only refer to with a name, you can actually pass them as a parameter to some Js function call. In this case an anonymous function, that has no own name, just the necessary parameterization with the resp=response parameter.

But even verbose coding wouldn't help you understand better, because you lack fundamental knowledge it doesn't really help you to explain from the top level, you need to get some bottom low level knowledge to understand how js works and how HTTP requests work, how client/server works before you get there.

are there any publically available PHP scripts that I can call to test from home?  
Well, first of all, it doesn't at all depend on being PHP, ajax makes a request to a URL, and that can also be a static HTML file, an image, PDF, anything. I assume you look for something bringing back a resp value, that you can see as data and "function result". Well, in the original meaning of ajax the result typically was the X, XML. Today I bet in terms of data the most often response rather is JSON, but also lots of HTML, that's simply put into the HTML of the current web page.

Anyway, the typical public resources of things you can request with ajax (besides many other means) are Web APIs, and there are loads of them you can find in https://www.programmableweb.com/category/all/apis

Again, it takes lots of background knowledge to get there, but here's a starter example to get some more complex JSON and display title and author of a book you know the isbn number:

Booksearch.html
<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
	<title>Book search</title>
  </head>
  <body> 
  <form name="book" action="" method="GET">
  <input type="text" name="isbn">
  <input type="submit" value="search">
  </form>
   
  <div id='bookinfo'></div>
  </html>

<script>$(function() {
  $('form').submit(function(e) {
    e.preventDefault();
    data = {
      q: 'isbn:'+this.isbn.value
    }
    $.get('https://www.googleapis.com/books/v1/volumes', data, function(resp, status, xhr) {
      //alert(status);
      if (xhr.status!=200) {
        alert('Oops something was wrong with your request, status code:'+xhr.status);
      }
	  
	  bookinfo = resp.items[0].volumeInfo;
	  $('#bookinfo').html('<p>Title: '+bookinfo['title']+'</p><p>Author(s): '+bookinfo['authors']+'</p>');
	  
    }, 'JSON');
  });
});</script>
</body>
</html>

Open in new window


Save as booksearch.html file, you won't even need to run a web server, just double click and run in your default browser, then enter the ISBN 0747532699 and you should get the title and author of the first Harry Potter novel.

I just warn you, you'll be lost on how to change and adapt this to any other API and result structure to get out what you want to display. You should first learn to walk before you run.

One very general thing to notice is, in this example the target URL you query is not even revealing, whether it is PHP or anything else, it is some URL, that returns JSON as its result instead of the typical response with some HTML document and API endpoints as those URLs are specifically called can actually be PHP scripts, too. It's not important whether they return JSON, XML or HTML or anything else, you get some string you can work on anyway. The jQuery $get function is very helpful with the result, as it does not just give you that response as a big messy string, it decodes the JSON to an object you can work with. Well, to be honest, it mainly saves you one line of a JSON.parse() call, but I assume jQuery does do a bit more for you than just that.
When you later not only need to make requests to the PHP scripts, that are the gateway API to your company database, then you'll just need to find out, what they typically return and adapt to that format. PHP at least has a similar function to turn typical PHP variable types like objects and arrays into JSON, namely json_encode().

Bye, Olaf.
0
 
gr8gonzoConnect With a Mentor ConsultantCommented:
Use AJAX. jQuery will do this pretty well:

myphpscript.php:
<?php

if($_POST["function"] == "doSomething")
{
  echo doSomething();
}
elseif($_POST["function"] == "doSomethingElse")
{
  echo doSomethingElse();
}

function doSomething()
{
  echo "Something was done.";
}

function doSomethingElse()
{
  echo "Something else was done.";
}

Open in new window


HTML page:
...other HTML here...
...load up jQuery...

<script type="text/javascript">
$.ajax({
      url: "/path/to/myphpscript.php",
      data: {
        function: "doSomething"
      },
      type: "POST",
      cache: false,
      success: function(result){
         alert(result);
      }
   })
</script>

Open in new window

0
 
Olaf DoschkeConnect With a Mentor Software DeveloperCommented:
You could make use of call_user_func(), but this comes with a warning: call_user_func() doesn't only call user-defined functions (which definitions and what they allow to do are in your control), but also any native built-in functions, which opens all kinds of possibilities for execution of malicious code.

execfunction.php
<?php
//ob_start();
include 'functions.php';

$res = "pass in function name [and parameters]";
if (isset($_POST['function']) && is_callable($_POST['function'])) {
	$res = "{$_POST['function']} didn't work.";
	try {
		if (isset($_POST['parameters'])) {
		    if (is_array($_POST['parameters'])) {
				$res = call_user_func_array($_POST['function'],$_POST['parameters']);	
			} else {
				$res = call_user_func($_POST['function'],$_POST['parameters']);
			}
		} else {
				$res = call_user_func($_POST['function']);
		}
	}
	catch(Exception $e) { 
			// log exception
	}

}
//ob_end_clean();
exit(json_encode(array("result" => $res)));
?>

Open in new window


Can be called from a jQuery enabled page in the way gr8gonzo already showed. This example shows the usage of a built-in function:

$.ajax({
      url: "/path/to/execfunction.php",
      data: {
        function: "implode",
		parameters: [' ',['hello','world']]
      },
      type: "POST",
      cache: false,
      success: function(result){
         alert(result);
      }
   })

Open in new window


To make this more secure, one way could be to prefix all your own user-defined functions with yourname_ and require $_POST['function'] to always start with that prefix, or always add it to whatever function name passed in.

And about the usage: This example parameters: [' ',['hello','world']] already is quite complex, as any function needing more than one parameter needs call_user_func_array and the JSON of the ajax call, therefore, needs parameters to be a JSON array. The implode function needs a glue string to add between elements of an array and that array, so that is an array nested in that parameter array [' ',['hello','world']].

The ajax result is the JSON {"result":"hello world"}, which you can decode in JS with JSON.parse()

Bye, Olaf.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Olaf DoschkeConnect With a Mentor Software DeveloperCommented:
I am new to javascript and php, what are to tools I need to use to develop, test and implement javascript and php???
You might start off with something simpler than JS "calling a PHP function". What gr8gonzo and I here showed already is quite advanced ways of enabling a very flexible ajax call to do anything defined on the PHP side.

You typically don't call a specific PHP function, but a whole PHP script, which wouldn't need all that logic around it. If...
I enter the URL of the php into the web browser and a new window appears with the value I need to save
you don't even need a HTML page with Javascript to start with, you make a direct request to your PHP script, that'll just need a browser with a new empty tab. The "result" of that PHP request then can be as simple as a single number or string, but in the normal case would be a HTML document.

For starters the installation you'll need is a XAMPP, which installs a web server (Apache), MySQL database, PHP and more, Javascript is built-in in any browser, that needs no installation.

For programming in HTML/JS/CSS and PHP one of the best editors is PHPStorm. It has a lot of features perhaps over the top for beginners, so you might start out with a simple free editor like notepad++ or brackets.

Bye, Olaf.
0
 
gr8gonzoConnect With a Mentor ConsultantCommented:
I would stay away from trying to do anything dynamic if you are still a beginner with PHP and AJAX. If you don't do it correctly, you leave your site open to attack. Calling PHP functions from Javascript via AJAX is already risky as it is, so stick with hardcoded function names for now. Just my own opinion.
0
 
Olaf DoschkeConnect With a Mentor Software DeveloperCommented:
DCCoolBreeze,
I think you actually just meant making a request to a PHP script with "calling a php function". Terminology is hard for beginners. Calling a function is happening inside a php script, it's either executing a built-in function or your own defined functions, but it'll normally just be partial PHP code and caling a function is just one step in the overall code. When you start PHP you'll most likely even not define functions - not even talking about classes - you'll just run through a script and that's already fine to begin with. The name of the php script will be what you think of as "function" names, but, well, you technically request execution of a php script and see its response in the browser and less technically speaking you call your php script.

You can also start and learn PHP first by visiting https://www.codecademy.com/en/tracks/php and then build up from that. That doesn't even require any installation.Typically you should have some HTML knowledge ahead of PHP, but when you're eager to not only define some document layout and paragraphs and step right into the programming side of the web this short tutorial is good for getting started.

Edit: Once you have the basic concepts and your goal still really is as literally given, you can still come back and grab one of the solutions. gr8gonzos is easier to understand and safer in only executing specific function names. It's even not too tedious to extend it that way, as it's just adding one more elseif branch, which should be far less to do in comparison to writing all the function code, as that of course typically isn't just an echo statement but much more lines of code.

Bye, Olaf.
0
 
Julian HansenConnect With a Mentor Commented:
Tools:
Server: Apache + PHP
  Either install yourself your use WAMP / LAMP or a Bitnami pre-built stack.

Editor:
   Notepad++ (my tool of choice)

Helper scripts
   Reflection script: a script (in your case PHP) that reflects the data sent to a script. In its simplest form
[reflect.php]
<h2>GET</h2>
<?php echo "<pre>" . print_r($_GET, true) . "</pre>";?>
<h2>POST</h2>
<?php echo "<pre>" . print_r($_POST, true) . "</pre>";?>

Open in new window

You can expand to save to file, add other data (Cookies, Files etc)

Reflection scripts are useful to see what is actually being received by the script.

Browser:
  I prefer FireFox but Chrome works as well. Understand the console (F12) how to inspect network requests being sent - how to view the PARAMS and RESPONSE from those requests.
  FF also has the scratchpad which is useful for testing JavaScript / jQuery snippets
  Debugger: learn how to use this if you are serious about Javascript.

jQuery: Learn jQuery - it will save you a lot of time.

JSON: Understand what JSON is and why we use it to exchange data in AJAX calls

Onto your question.
JavaScript cannot directly call a PHP function - you have to make an HTTP request to the server to run the target script which then outputs a value which you can capture in the JavaScript function. As noted above use AJAX to do this.

I would advise against using call_user_func() - it can be made secure but the risk still exists that you open a massive security hole in your application.

With the situation you are describing you should take a look at RESTful requests and how to build a RESTful API. A RESTful API is one that has endpoints linked to specific requests (think URL's) and VERBS (GET / POST / PUT etc). The API endpoints exist to provide a specific function - you pass a parameter it returns a value (usually, but not always, as a JSON return).

Sample code
PHP Endpoint
api/getSpecialValue.php
<?php
// Ensure a valid parameter exists
$answer = isset($_GET['answer']) ? $_GET['answer'] : false;
$response = new stdClass;
$response->status = false;
if ($answer) {
  $response->status =  true;
  if ($answer == 1) {
     $response->message = "Yes";
  }
  else {
     $response->message = "No";
  }
}
die(json_encode($response));

Open in new window

Client side
<button class="action-button" data-value="1">Yes</button>
<button class="action-button" data-value="2">No</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
  $('.action-button').click(function(e) {
    e.preventDefault();
    data = {
      answer: $(this).data('value')
    }
    $.get('api/getSpecialValue.php', data, function(resp) {
      if (resp.status) {
        alert('You clicked ' + resp.message);
      }
      else {
        alert('Oops something was wrong with your request');
      }
    }, 'JSON');
  });
});
</script>

Open in new window

You can see a working sample here
0
 
DCCoolBreezeAuthor Commented:
Julian,

It looks like the solution you provide may be what I am looking for.  Question though.  what javascript variable will hold the data.  I am doing this for work.  They use adobe capitivate for training and it uses javascript.  I want to get one data value from the company database by calling a PHP script (I understand now that it is not a function but it is referred to as a script).  So I want to execute the php script and save the returned value to a javascript variable.  Then I can use the Captivate API to pull that value from the javascript variable to captivate and display it.

It looks like jQuery is the way to go.

Also, are there any publically available php scripts that I can call to test from home?  maybe from google or some other company.... say a publically available date/time php script that I could use for testing from home.
0
 
Julian HansenConnect With a Mentor Commented:
With AJAX programming is asynchronous which means you initiate your call to the script and then setup a callback to handle the response.

In my sample this is done on line 11 the $.get works as follows

$.get ( 
   [THE URL OF THE SCRIPT], 
   [THE DATA TO SEND TO THE SCRIPT], 
   [THE CALL BACK FUNCTION], 
   [IF YOU ARE SENDING JSON BACK THEN ADD THE 'JSON' PARAMETER]
);

Open in new window

In the above example we have this
$.get('api/getSpecialValue.php', data, function(resp) {

Open in new window

The callback function is where the magic happens. Your JavaScript (with respect to the data you are retrieving) remains dormant until this fires
function(resp) {
   // This code will be called when the AJAX call completes
   // Anything returned by the script will be in the 'resp' parameter
   // Here is where you would process the return from the script
}

Open in new window

Hopefully that makes more sense.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.