开发者

Creating jQuery AJAX requests to a PHP function

So far when creating AJAX requests I ha开发者_如何学JAVAve been posting to a separate PHP file. Is it possible to create a jQuery AJAX request that calls a PHP function rather than posts to a separate page?

If you could send me any examples or documentation would be great.


I believe there's a fundamental misunderstanding of how the technology works here.

AJAX (Javascript), Flash, or any client-sided technology cannot directly call PHP functions (or other languages running on the server). This is true for going the other way around as well (eg: PHP can't call JS functions).

Client and server codes reside on different machines, and they communicate through the HTTP protocol (or what have you). HTTP works roughly like this:

Creating jQuery AJAX requests to a PHP function

Client (eg: browser) sends a REQUEST -> Server processes request and sends a RESPONSE -> Client gets and displays and/or processes the response

You have to see these requests and responses as messages. Messages cannot call functions on a server-side language directly 1, but can furnish enough information for them to do so and get a meaningful message back from the server.

So you could have a handler that processes and dispatches these requests, like so:

// ajax_handler.php
switch ($_POST['action']) {
    case 'post_comment':
        post_comment($_POST['content']);
        break;
    case '....':
        some_function();
        break;
    default:
        output_error('invalid request');
        break;
}

Then just have your client post requests to this centralized handler with the correct parameters. Then the handler decides what functions to call on the server side, and finally it sends a response back to the client.


1 Technically there are remote procedure calls (RPCs), but these can get messy.


AJAX requests call a URL (make a HTTP request), not a file, in most cases the URL is translated by the server to point at a file (or a php script in your case), but everything that happens from the HTTP request to the response that is received is up to you (on your server).

There are many PHP frameworks that map URL's to specific php functions, AJAX is just an asynchronous way to access a URL and receive a response.

Said URL CAN trigger the server to call a specific function and send back a response. But it is up to you to structure your URL's and server side code as such.


If you're asking whether you can call any arbitrary PHP function with AJAX the answer is no*, for obvious security reasons (in addition to the technical reasons). You could make a PHP script that does different things depending on what parameter it's given (for example, execute a single function) if you don't want to create multiple separate files.

*Although you could make a script that would execute any arbitrary PHP command coming from the client, but that would be very, very, very unwise.


Short answer is "no" but the real answer is that you can fake it. NullUserException's answer is good. You create a server that will take the function name and its parameters. Then the server executes the function, and returns the value.

This was done a while back via a protocol called XML-RPC. There was also an effort called JSON-RPC that used some JS techniques.

One things that's cool about JS is that you can do things like this:

var base64_decode = create_remote_call('base64_decode');

function create_remote_call(name) {
  return function(x) { 
    jQuery.getJSON('url/server.php',
                   {func:name,arg:x},
                   function(d){return d;}); 
  } 
}

A call to base64_decode('sarefdsfsaes') will make a ajax request and return the value.

That code probably won't work because it hasn't been tested, but it's a function that produces a function that will call the server, and then return the value. Handling more than one argument requires more work.

All that said... in my experience, it's usually good to make all network communications explicit instead of disguising it as a regular function.


you may achieve the same result using a bridge, like my phery library http://phery-php-ajax.net you can call PHP functions directly from Javascript and deal with the value. The AJAX is bound to DOM elements, so you can manipulate the calling DOM or just use jQuery from the PHP side. An example would be:

Phery::instance()->set(array(
  'phpfunction' => function(){
     return PheryResponse::factory()->jquery('body')->addClass('whoops');
  }
))->process();

and in the javascript side (or HTML)

phery.remote('phpfunction');  

the equivalent to the https://stackoverflow.com/a/7016986/647380 from John Kawakami answer, using phery is:

function base64($data){
  return !empty($data['encode']) ? base64_encode($data['content']) : base64_decode($data['content']);
}

Phery::instance()->set(array(
  'base64' => 'base64'
))->process();
function base64(content, decode, output){
  phery.remote('base64', {'content': content, 'encode': decode ? 1 : 0}, {'type':'text'}).done(output);
}

base64('asdf', false, function(data){
  console.log(data); // or assign to some variable
});

since AJAX is asynchronous and you can't just return a value from the AJAX call, you need a callback, but this would suffice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜