This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript.
<?php
if(isset($_POST['something'] {
//do something
}
?>
to this
<?php
function test() {
if(isset($_POST['something'] {
//do something.
}
}
?>
How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed.
Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
I believe that's a simple incarnation of the Command pattern.
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).
You basically send a JSON string in a specific format to the server, e.g.
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.
You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).
If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:
function test() {
// function code
}
test();
Or, use a PHP include:
include 'functions.php'; // functions.php has the test function
test();
You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.
Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).
You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net
Phery::instance()->set(array(
'phpfunction' => function($data){
/* Do your thing */
return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
}
))->process();
The javascript would be simple as
phery.remote('phpfunction');
You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):
function mcrypt(variable, content, key){
phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}
//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');
and in the server
Phery::instance()->set(array(
'mcrypt_encrypt' => function($data){
$r = new PheryResponse;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
return $r->set_var($data['variable'], $encrypted);
// or call a callback with the data, $r->call($data['callback'], $encrypted);
}
))->process();
Now the variable will have the encrypted data.
I have php function that checks if an entry exists in my database that I call with class::checkThis($my_entry);
In my script javascript is used to determined the name of the folder I am selecting, so $my_entry is supposed to look like this :
(in normal is determined by php and the part in bold is what is determined by javascript)
C:/library/user/apatik/folder1
As you guess I can't find a working way to mix up thoses languages, and I don't really have any experience in javascript yet to figure out this.
The php code that returns the first part of the path is simply $_SESSION['cwd'].'/' and the javascript variable that returns the selected folder's name is data_name and is determined by var data_name = $(this).attr('data-name');
Is there a way to get something like if (class::checkThis($_SESSION['cwd'].'/'.data_name) == true) ?
None of what I tried so far worked and I'm having troubles finding an alternative.
Thanks for the help
You'll need to make an AJAX request to accomplish this. You'll load the page as normal, except for the dynamic part. Then you can populate the dynamic part (I've illustrated it as #content here) based on the result of the AJAX call:
var data_name = $(this).attr('data-name');
...
$.ajax('http://example.com/my_php_script.php?data_name=' + data_name)
.done(function(data){
// "data" is the resulting output of the PHP script
$('#content').append(data);
});
NOTE: The solution above uses jQuery.
Then, in your my_php_script.php, you can do something like this:
if (class::checkThis($_SESSION['cwd'] . '/' . $_GET['data_name']) == true) {
...
}
Ajax jQuery is your best solution.
This one using post method with event, just for reference...
Am I exist?
Am I exist too?
$('.anchor').click(function(){
var data_name = "name=" + $(this).attr('data-name');
$.ajax({
type: "POST",
url: "is_exist.php",
data: data_name,
success: function (data) {
alert(data.response);
}
});
};
is_exist.php
if(isset($_POST['name'])){
$data['response'] = class::checkThis($_SESSION['cwd'].'/'.$_POST['name']) == true ? "exist" : "buried";
echo json_encode($data);
}
Currently I've been Ajaxing a route that renders a Twig template via a Controller and injecting it into the page - all is well.
return $this->render('MyBundle:Requests:results.html.twig', array('system' => $lc_system));
However, in my JavaScript, I would like to get some extra information returned... Specifically I want a count of the results, so I can check it against a JS variable. I could put it into the twig file and then get it in JS that way, but it feels horrible.
Is there any way to get any variables sent down with the Ajax response, or a best practice way to approach this.
Use echo in your PHP function instead of return.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function() {
doSomething(data); //Data is output
}
});
In PHP:
<?php
$output = some_function();
echo $output;
?>
It's an argument passed to your success function.
The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation.
If you weren't returning actual page content in your response, I'd say to return a JSON response and call it good. But since you're already using your response body for some HTML, you have to come up with another way to return the info.
One approach I've used in the past is to add a custom HTTP header and return my "meta" values that way. First, set the header in your PHP (make sure this happens before any output):
header('X-MyCustomHeader: ' . $phpVar);
Then, you can get it in your jQuery success method like this:
success: function(result, status, xhr) {
var customHeader = xhr.getResponseHeader('X-MyCustomHeader'));
}
While you can technically name your custom header anything you want, see this post for best practice/naming convention ideas:
Custom HTTP headers : naming conventions
I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever¶m2=whatever¶m3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'¶m2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo¶m2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.
I have php script with 5 function. The script gets "request_type" "user_id" and "youtube_id" and execute a function (one of a five) suitable to the "request_type"
Each function returns me json.
Now on the client side i have this javascript function. I want it to be generic as much as possible, Which mean that i want it to get data from php and return it as object.
function request_to_server(f_request_type, f_user_id, f_youtube_id) {
var my_answer;
$.ajax({
type : "POST",
dataType : "json",
url : "http://example.com/youtube_save.php",
data : {request_type: f_request_type, user_id : f_user_id, youtube_id:f_youtube_id },
success: function(response) {
my_answer = JSON.parse( response );
}
});
return my_answer;
}
Here is the example of another function that get this object
function show_button_or_not() {
var user_id = $('#hold_user_id').val();
var answer = request_to_server('show_button','89',"lala");
if(answer.success) {
alert("yes");
} else {
alert("no");
}
}
But as i said, the php can return different kinds of json. It can have (optional) response.success, response.book, response.author.
Anyone can explain how to do that?
On the server side, in PHP, add the request_type to the json response so that your client side AJAX callback will receive the request_type that had initiated the AJAX in the first place.
All you have to do after that is evaluate the request_type (with a switch case maybe) and perform the necessary actions for that case (request_type).
But honestly, I wouldn't try to make the AJAX request and callback "generic" and having 1 URL pointing to 5 php functions it's not best practice for a web api.