Does anyone know how I can directly access a function from a PHP class through AJAX (using jQuery).
PHP:
class Blah
{
function __construct()
{
}
function doSomething(data)
{
echo "I am not an animal";
}
}
jQuery:
$.ajax({
url: myClass.php,
data: Blah.doSomething(); "or" Blah->doSomething() "or whatever"
});
I know this is a crude example, i'm just trying to illustrate a point, I hope you can get the gist of my question.
At the moment i'm doing something along these lines:
$.ajax({
url: myClass.php,
data: data : { 'type':'doSomething' }
});
||
if(POST['data']['type'] == 'doSomething')
{
$this->doSomething();
}
And I don't like it...
You need to create an object of that class and then invoke the methods you need.
The class declaration doesn't not execute any code.
For example, you can add this below the class:
class Blah { ... }
$b = new Blah();
$b->doSomething();
UPDATE:
If you want to invoke the method sent in POST, you can use the function call_user_function:
$method_name = $_POST['method'];
$b->{$method_name}();
See here more details: http://php.net/manual/en/function.call-user-func.php
i don't know why do you like to do so.
its not a good programming practice.
but you can try something like this
$.ajax({
url: myClass.php,
data: {'call':'Blah.doSomething', 'args':5}
});
and in server side you can do like
$fun = explode('.', $call);
$function = array($fun[0], $fun[1]);
if (is_callable($function)) {
$response = call_user_func_array($function, $args);
}
echo $response;
Right now I can't think of any better way than PHP outputting results in json and you get the result via getJSON
I concur with mazzucci's answer. I hope this is a bit more complete.
PHP:
class SomeClass{
//definintion
}
$obj = new SomeClass();
$obj->doStuff();
HTML:
<input type="button" onclick="<?php $obj->doStuff(); ?>" id="btnAdd" value="Click Me" />
Also, you can look into xajax, a nice little framework that simplifies php<->javascript interaction. It can call js functions from php as well. Here's the link: http://www.xajax-project.org/en/home/
**Your class**
class Blah {
function doSomething(data) {
echo "I am not an animal, I'm a ".data;
}
}
**Ajax call in other document**
$.ajax({
url: example.php,
data: info='beast'
success: data () { ...
});
**in example.php**
include (class.blah.php);
$obj = new SomeClass();
$obj ->doStuff($_GET['info']);
It's not possible. What you currently have is probably the best way.
Related
I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}
I have a php file func.php where I defined many functions let's say :
<? php
function func1($data){
return $data+1;
}
?>
I want to call the function func1 using ajax. thank you for your help
You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});
You should call your php script through an ajax request, using jQuery like:
Javascript:
$.ajax({
url: "script.php",
data: { param1: "value1", param2: "value2" },
type: "GET",
context: document.body
}).done(function() {
// your code goes here
});
You could give your parameters through data property of ajax object.
Php
// you can do isset check before
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// validate // sanitize // save to db // blah blah // do something with params
More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/
It's a bit more complicated, but I will try to shrink it down to the basics.
You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:
The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.
The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.
Add the following code along with your functions:
if(isset($_GET['func']))
{
$func=$_GET['func'];
if(function_exists($func))
{
$args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
$result=call_user_func_array($func,$args);
}
else
$result=array('error'=>"Unknown Function $func!");
}
else
$result=array('error'=>"No function name provided!");
echo json_encode($result);
However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.
Your example function, for instance, should look something like this:
function func1(){
$data=func_get_args();
if(count($data)) // at least one -- rest will be ignored
return $data[0]+1;
else
return array('error'=>__FUNCTION__."() expects an argument!");
}
Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.
Yes you can !
here my code :
$.ajax({
type: "POST",
url: "ajax.php",
data: { kode: $(this).val(), func: 'my_func' },
success: function(response) {
//any success method here
}
});
and here the code in php to receive what function to call.
$post = (object) $_POST;
if(!$post)
return false;
$func = $post->func;
return $func($post);
function my_func($post) {
$json['any_data'] = false;
if($post->kode == 'ND'){
$json['any_data'] = 'ND-'.date('Y');
}
echo json_encode($json);
}
Hope it help you out bro... :D
i am working on a core php project in which i want to call php function from javascript using ajax call request.i tried this but its not work.
js file:
$.ajax({
type: "POST",
data: data,
url:"/rootfolder/subfolder/action.php/test",
success:function(response)
{
if(response == 'true')
{
window.location.assign("home.html");
}
else
{
alert("wrong credencials");
}
},
failure:function(response)
{
alert("there is an error.");
}
});
php file:
<?php
include("../connection.php");
function test()
{
//some stuff
}
?>
please suggest some solution or provide any refrence.thanx in advance.
You can't call a PHP function from JavaScript. You can only make an HTTP request. That HTTP request might be handled by a PHP program. There is no built-in PHP feature that will let you specify a particular function to call.
You can examine $_SERVER['PATH_INFO'] to determine what data is in the URL after the script name and use that to determine what the PHP program should do.
if ($_SERVER['PATH_INFO'] === "test") {
test();
}
you have declared the test function but haven't called it, I think the error is from the php side.
<?php
include("../connection.php");
test();//call the function
function test()//this is just function decleration
{
//some stuff
}
?>
Just use a URL variable called method
/subfolder/action.php?method=test
And then in your PHP use that variable to call the function
<?php
$function = $_GET['method'];
$function();
function test()
{
//some stuff
}
......
?>
There could be other solutions too...
I'm running into trouble accessing global variables when I make an AJAX call to a php function in the MediaWiki framework.
My jQuery AJAX call looks like this:
jQuery.ajax({
url: 'GeneralFunctions.php',
type: 'GET',
dataType: 'json',
data: {
text: anchorText
},
success: function (data) {
alert("data: " + data);
}
});
My GeneralFunctions.php file looks like this:
<?php
if (isset($_GET['text'])) {
jsonInlineParse((string) $_GET['text']);
}
function jsonInlineParse($wikiText)
{
global $wgOut;
$return = $wgOut->parseInline($wikiText); //fails here
echo json_encode($return);
}
?>
When I run the jQuery call through a click event I get as far as the parseInline() function. The global variable is never defined in the scope and I get the error:
Fatal error: Call to a member function parseInline() on a non-object in /path/to/file/GeneralFunctions.php on line 54
I'm not sure how to make the parse call and define the global variable when the AJAX call is made?
UPDATE
$wgOut is the OutputPage object associated with MediaWiki. It holds all the HTML of the page and is used throughout the MediaWiki framework to add content to a page or article. It is used on the server side to create customized output for wiki articles. I use it to create forms or add HTML on many of our wikis.
More info here: http://www.mediawiki.org/wiki/Manual:$wgOut
UPDATE 2
#Juhana I changed my function to look like this which results in the same error as before. Each echo outputs "NULL".
<?php
function jsonInlineParse($wikiText)
{
include_once '/path/to/file/includes/OutputPage.php';
include_once '/path/to/file/includes/parser/Parser.php';
echo var_dump($wgOut);
global $wgOut;
echo var_dump($wgOut);
$return = $wgOut->parseInline($wikiText);
echo $return;
echo json_encode($return);
}
?>
I took a different approach after running into global variable problems. I changed the AJAX call I was making and the code below works very well for me. I'm using the editable jquery table you can find here.
PHP
function ajax_parse(){
global $wgRequest;
if($wgRequest->wasPosted()){
$text = $wgRequest->getVal("text");
wfDebug("Recieving::::".$text);
if(!strpos($text, "href")){
$text = myInlineParse($text);
$text = str_replace("<pre>", "", $text);
$text = str_replace("</pre>", "", $text);
}
wfDebug("Returning::::".$text);
echo $text;
}
exit;
}
function myInlineParse( $wikiText ) {
global $wgOut;
return $wgOut->parseInline( $wikiText );
}
JavaScript
// inject wikitext after hitting save
function postSave(o) {
var response = new Array("");
for(var i=0;i<o.row.length;i++){
new Ajax.Request(wgScript +'/Special:EditClass/ajax_parse',
{
asynchronous: false,
parameters: {'text': o.row[i].innerHTML},
onSuccess: function(text){
response.push(text.responseText);
}
}
);
}
return response;
}
For whatever reasons, extensions don't seem to have access to $wgOut. I solved this for my extension by using the hook: OutputPageParserOutput for the code I needed output (I needed to inject some scripts and stylesheets as well as using another hook to modify links and didn't want to bother with Resource_Loader though it is useful and recommended):
$wgHooks['OutputPageParserOutput'][] = array($this, 'doOutputPageParserOutput'); // 'doOutputPageParserOutput' defined as method in my class
As with other hooks, you can get rid of the array in favor of just a function name if you don't want to execute within a class.
It's kind of embarassing that I find it so difficult to learn JavaScript, but ..
Let's say I have a really simple controller like this:
class front extends Controller {
public function __construct()
{
parent::Controller();
}
public function index()
{
//nothing!
}
public function test () {
$someNumber = $this->input->post('someNumber');
if ($someNumber == 12) { return TRUE; }
}
}
Yes, that could probably be written better, haha.
What I want to know is - how could I use JavaScript to submit a number in a form (I'll worry about validation and models later), how should I write my test() function so that it returns something readable by the JavaScript (I'm assuming return TRUE probably wouldn't work, perhaps XML or JSON or something like that?), and how do I access the data with the JavaScript?
I know there are frameworks like jQuery that will help with this, but right now I'd just like to understand it at the simplest level and all the tutorials and guides I've found so far are way too in depth for me. An example in jQuery or whatever would be good too.
Thanks a lot :)
you would just print it out basically, and re-capture that information via javascript:
public function test() {
$somenumber = $this->input->post('someNumber');
if ($somenumber == 12) {
print "Number is 12";
} else {
print "Number is not 12";
}
}
your javascript might look something like this:
var xhr;
xhr = new XMLHTTPRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// this is where the return information is
alert('Status: '+xhr.status+' Response: '+xhr.responseText);
}
}
xhr.open('POST', '/front/test');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('someNumber=12');
the code above doesn't take into account browser specific issues, but should run on firefox/ie7 at least i believe.
here's a jQuery example of all the above:
var options = {
'someNumber' : 12
}
$.post('/front/test', options, function(data) {
alert(data); // should print "Number is 12"
});
I've also found in CodeIgniter that 'XMLHTTPRequest' isn't returned in the response headers, when using the standard Javascript AJAX call as mentioned above.
$this->input->is_ajax_request();
The input helper doesn't ever return true unless you use jQuery to handle the AJAX POST request.
I also tried the method in this article which didn't work: http://developer.practicalecommerce.com/articles/1810-The-Benefit-of-Putting-AJAX-and-CodeIgniter-PHP-Together
This is what I used in the end:
var query_params = $('#data-form').serialize();
$.ajax({
type: 'POST',
url: 'process_this.php",
data: queryParams,
context: document.body,
success: function(){
alert('complete'); // or whatever here
}
Possibly caused by a config issue to do with my CI install, haven't had time to investigate yet.