Cannot Access Global PHP Variable in jQuery.ajax call in MediaWiki - php

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.

Related

Ajax call not working out in wordpress

I referred to some examples online and modified functions.php and the front end template to fire an ajax call to fetch some data. But I've hard time understanding on hoe the data is returned from the requested url.
At the end of functions.php, I added,
wp_enqueue_script('jquery');
function myFunction(){
echo "hi";
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
In my custom template page, I added,
var datavalue = 'test data string';
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: { 'datavar' : datavalue }
}).success(function(data) {
console.log("successfully run ajax request..." + data);
}).done(function(){
console.log("I am from done function");
}).fail(function(){
console.log("I am from fail function.");
}).always(function(){
console.log("I am from always function");
});
});
After running it, I get these response.
I am from fail function.
I am from always function
I don't understand how to fetch data from a specific url and display the result in ajax's success function.
I don't even know how the function defined in function.php would be called by this ajax call? How are they related?
Please explain. Also I would like to fire ajax call to query database by passing keyword, how can I do that in wordpress?
Your AJAX function should include an action parameter to tell admin-ajax which function you would like to execute.
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
}
(or, if you are set up for it, then you can include it in your url, as below)
url: "/wp-admin/admin-ajax.php?action=myFunction"
Also, your function in functions.php should be written in PHP:
function myFunction(){
echo 'hello';
die();
}
You have to use a action on ajax like.
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
'datavar' : datavalue,
}
});
PHP function need to edit.
function myFunction(){
echo 'success calling functions';
wp_die();
}
you are not passing the "action" parameter in "data". Which contains callback function's name. Please check the attached link.
https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/
In this you've to make a callback functions.
Wordpress dsnt work with the specific url.
But if you still want to use the specific url. Follow the steps:-
1. Make a wordpress template.
2. Add your specific url code there.
3. Make a page in the admin panel and assign the template you've created above.
4. Now the permalink of that page can be used as a specific url in the jQuery ajax.
In addition to above answers, in your function.php, make use of $_REQUEST. The $_REQUEST contains all the data sent via AJAX from the Javascript call. Something like this
function myFunction() {
if ( isset($_REQUEST) ) {
{
global $wpdb;
$keyword = $_REQUEST["keyword"];
if($keyword){
$query = "
SELECT `$keyword`, COUNT($keyword) AS Total
FROM `profileinfo` GROUP BY `$keyword`
";
$result = $wpdb->get_results($query);
$data = array();
foreach($result as $row)
{
$data[] = $row
}
echo json_encode($data);
}
}
}
die();
}
add_action( 'wp_ajax_myFunction', 'myFunction' );
add_action('wp_ajax_nopriv_myFunction', 'myFunction');

Calling php function with ajax and passing return value to div

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();
}
}

Contao 2.11 call to module via ajax

I have question about call to my module action via ajax.
I'd like call to class in my module via ajax. But best solution for me is call to clean class. Not extends Module.
I don't know hot can I make url without add article to database and add module to him.
I use JQuery instead mooTools but js framework is not important. Most important is call to php class by ajax.
I have ajax module. But if I call to ajax.php required is module id from tl_module table. I don't want use this table. (Ajax will be very often calling, I prefer to don't load all contao mechanism. It should be very fast).
Thanks in advance for answers.
I found the answer for Contao >3.x in a GitHub issuse(german)
At first do in your Front-end Template:
<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";
$(document).ready(function(){
$("#trigger").click(function(event){
$.post(
'<?php echo \Contao\Environment::get('requestUri')?>',
data,
function(responseText) {
alert(responseText);
}
).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
event.preventDefault();
});
});</script>
Important is the
- data["REQUEST_TOKEN"] -> if you do not add it, the POST-request will not reach your module:
public function generate()
{
if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
$this->myGenerateAjax();
exit;
}
return parent::generate();
}
//do in frontend
protected function compile()
{
...
}
public function myGenerateAjax()
{
// Ajax Requests verarbeiten
if(\Environment::get('isAjaxRequest')) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array(1, 2, 3));
exit;
}
}
If you want to do the ajax via GET you do not need the reqest token but the jquery funktion $get();
I would suggest you to use Simple_Ajax extension.
In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls.
It works with Contao 2.11 and you can call your php class with it.
I find it much easier to use than ajax.php .
You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html
Copy SimpleAjax.php to Contao's root folder.
Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :
class AjaxRequestClass extends System
{
public function AjaxRequestMethod()
{
if ($this->Input->post('type') == 'ajaxsimple' )
{
// DO YOUR STUFF HERE
exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
}
}
}
Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
Now you can easily make ajax calls with simply posting data to SimpleAjax.php:
$.ajax({
type: "POST",
url: "SimpleAjax.php",
data: { type: "ajaxsimple" },
success: function(result)
{
//DO YOUR STUFF HERE
}

how to make ajax request from javascript for core php function

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...

How to get the parameter sending by post method in php included file?

Good day. I am having the following code snippet in init.php.
<?php
include_once("config.php");
include_once(__SITE_PATH . 'view/' . $_REQUEST['page'] . EXT);
$loginobj = new $_REQUEST['page']($_REQUEST['billingentitynuber']);
$text = $loginobj->$_REQUEST['content']();
echo $text;
?>
In Jquery I am having the function Jquery_event.js
$("#entertoapp").click(function()
{
alert($("#btval").val());
$.ajax({
type: "POST",
url: "init.php?page=processing&content=enterintoapplication&btval=" + $("#btval").val(),
success: function(msg) {
alert(msg);
if(msg==1)
window.location.href='index.php?page=processing&content=mycontent';
}
});
});
In processing.php I am having
<?php
class processing
{
public function enterintoapplication()
{
global $billingentityname;
$_SESSION['btval'] = $billingentityname;
echo $billingentityname;
}
}
?>
My problem is I am getting all the parameters in the init.php. But when I call a function I need to get in the processing.php in the enterintoapplication function (i.e. I am expecting btval in the enterintoapplication function). How can I achieve this? I tried to get $_REQUEST['btval'] within the function. But I didn't get.
Try assigning the values to variables, for example this works for PHP 4:
class processing
{
function enterintoapplication()
{
echo "hello";
}
}
$className="processing";
$functionName="enterintoapplication";
$loginobj=new $className();
$text=$loginobj->$functionName();
echo $text;
Paste it here to verify it works: http://writecodeonline.com/php/
Pls,pay attention to "$functionName", here it keeps the "$".
Nevertheless, for security reasons, you should be attentive to what people can do if they change the value "page".
I don't understand your problem correctly, but with some general information, you should get out of this.
$_REQUEST is a superglobal, that means that variable will always be accessible from everywhere within your script. If your problem is you can't find the btval variable that was in your URL, you are doing something else wrong. If your url=http://someUrl/test.php?btval=banana you should always get banana if you evaluate $_REQUEST['btval']. $_SESSION is another superglobal to access the PHP session, and has nothing to do with URL variables.
My guess:
Try changing
$_SESSION['btval'] = $billingentityname;
into
$billingentityname = $_REQUEST['btval'];
In that case, your real mistake was that you've put the two variables in this assignment in the incorrect order. $a = $b means: put the contents of $b into $a.

Categories