Question

I have file called functions.js included in page. I have there line:

ajaxRequest.open("GET", "save.php?json=" + jsonstring + "&rand=" + rand, true);

How to call php method by ajaxRequest? I also want to call this by php function from class (for example save($json, $rand))

Pseudo code:

ajaxRequest.callPhpFunction( function{ Class::save($json, $rand) }  )

EDIT:

Maybe XAJAX (http://www.xajax-project.org/) is solution?

Was it helpful?

Solution

Your XHR (XML Http Request) makes an HTTP Request. This is the only way your JavaScript and your PHP will communicate (we do not talk about sockets here).

YOU have to code your back-end to do the good action when an URL is called, and seeing what you want to achieve, you maybe want to take a look at the REST method which approximately correspond to want you are looking for.

OTHER TIPS

You won't be able to call a PHP function from a JS script. You should read about server side vs client side scripting.

On the other hand, what you could do is something like this:

phpfunctions.php

$function = $_GET['func'];
$result = Class::$function($_GET['json'], $_GET['rand']);
echo json_encode($result);

filewithjs.html

$.ajax({
 url: "phpfunctions.php", 
 data: {
  json: {somedata: 1}, 
  rand: 1, 
  func: "phpfunction"
 }, 
 type: 'GET',
 success: function(resp) {
  //Do something with the result
 }
});

But be aware that this might be a security hole.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top