Drupal module jQuery PHP script location issue - php

I am developing a module which has a jQuery script with some AJAX code. The ajax code calls a php script located in the same location as the jQuery script.
My problem is, AJAX appends the domain name in front of the PHP script name and of course, my script does not exist at that location and so the process breaks.
The AJAX code is as follows:
$(document).ready(
function(){
$.ajax({
url: "/testscript.core.php",
asych: false,
success: function($data){
$('textarea#edit-simplechat-messages').text( $data );
}
});
}
);
And the following is the link that shows up in firebug:
http://testsite.co.uk/testscript.core.php
Again, the jQuery script and the php script are in the same directory.
I thought the forward slash before my php script name would eliminate the domain name but it did not work.

Use
Drupal.settings.basePath
url: Drupal.settings.basePath+'your file path',
This link might be useful
http://www.akchauhan.com/how-know-base-path-of-drupal-in-javascript/
EDIT :
Or you can use this approach if you are creating your own custom module then follow these steps
1] First create your module, Here my module name is "mymodule", So i created a file name mymodule.module
<?php
function mymodule_init() {
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
// this call my js file when module is initialized.
}
function mymodule_menu(){
$items = array();
$items['mypath'] = array(
'title' => t('To get series of the selected brand'),
'page callback' => 'mymodule_page',
'page arguments' => array(1),
// get test_parameter from url, which is your first argument
//http://domain.com/mypath/test_parameter
// here mypath is arg(0), and test_parameter is arg(1)
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mymodule_page($termID){
return drupal_json(array('message'=> $itemID));
}
2] Secondly create js file with the same name so name it mymodule.js under the same module file.
// $Id$
Drupal.behaviors.mymodule = function (context) {
var $basepath = Drupal.settings.basePath;
$('selector').change(function(e){
$.ajax({
type: 'POST',
url: $basepath+'mypath/test_parameter',
// test_parameter :value you are sending to you module.
dataType:'json',
cache:false,
beforeSend:function(){
},
success:function(data){
alert(data.message);
},
complete:function(){
},
error:function(xhr, status, error){
}
});
});
}
Notice in js file i have used mypath. your js file will call this path which is defined in the hook_menu().

the way it is now it looks like your problem is the slash before the file name.. that means "domain web root"

Related

Wordpress - backend AJAX call returning 0

I have create a backend plugin for my website and I would like it to work with AJAX. But all I am getting from the AJAX response is readyState: 4 and responseText: 0.
script.js
jQuery(document).ready(function($){
$.ajax({
url: ajaxurl,
type: "POST",
data: {
action: 'my_action',
param: 'st1'
},
error : function(response){
console.log(response);
},
success : function(response){
console.log(response);
}
});
});
members_loop.php
add_action('wp_ajax_my_action', 'my_ajax_action_function');
add_action('wp_ajax_nopriv_my_action', 'my_ajax_action_function');
function my_ajax_action_function(){
$reponse = array();
if(!empty($_POST['param'])){
$response['response'] = "I've get the param a its value is ".$_POST['param'].' and the plugin url is '.plugins_url();
} else {
$response['response'] = "You didn't send the param";
}
header( "Content-Type: application/json" );
echo json_encode($response);
wp_die();
}
I am using three files inside my plugin to do this, I have my plugin.php file where I declare my plugin and enqueue my script.js file. Then I have a templates file with two folders inside it one being members_loop.php and the other index.php (The "homepage" for the plugin). Then I have an assets file with my script.js file. Not sure if this information is needed but I don't think my ajax call is wrong so I'm wondering what is going wrong.
Issue Update
I just cut and paste the my_ajax_my_action funciton and the actions to the plugin.php file where I declare the plugin and now it works. So how do I get it to work in an external file? do I have to require the members_loop.php file inside the plugin.php file?
If your file path is "/wp-content/plugins/your_plugin/members_loop.php", so inside file "plugin.php" add require_once plugin_dir_path( __FILE__ ) . 'members_loop.php'; or require_once dirname(__FILE__) . '/members_loop.php';

Use ajax/json in yii framework

Im trying to make a webshop in Yii framework. Now i want to unset a session when a user clicks on a icon.
I currently have it working that is sends a json call to a file, but the url in the json call is being rewrited by my htaccess i think.
JSON call:
$(document).ready(function(){
$('.glyphicon-trash').click(function(){
$.getJSON("ajax/load.php?action=unset&element="+$(this).parent(), function(data) {
alert(data.message);
});
});
});
Error i get:
GET http://mydomain.nl/my/path/to/site/ajax/load 404 (Not Found)
But it's not load, its load.php! But my htaccess rewrites that url..
.htaccess
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
Other ways of implementing ajax calls in Yii are also good, only i need alot of explanation then.
You can achieve these by core yii-ajax but if you want much work with ajax then you can use the core YII library with "renderPartial" ajax and widgets.
This is the core ajax call with yii
Add below line in your view.
<input type="hidden" id="baseUrl" value="<?php echo Yii::app()->getBaseUrl(true);?>">
Add below line in your js file.
function changeData(val1){
var baseUrl = $('#baseUrl').val();
var urlCI = baseUrl+'/Controller/actionMethod/;
$.ajax({
type: "GET",
url: urlCI,
data:{
'action':'unset',
'element' : 'someValue'
},
success: function(response) {
if(response!=''){
//do whatever work you want
return true;
}
else{
return false;
}
}
});
}
Okay i got this working now, i made a file under site view. Now i call it like:
$(document).ready(function(){
$('.glyphicon-trash').click(function(){
var session = 'session';
$.getJSON("<?php echo Yii::app()->baseurl; ?>/load?action=unset&session="+session, function(data) {
location.reload(true); //<---- this one does not work tho...
});
setInterval(function(){location.reload(true);}, 500);
});
});
You must not hardcode url's. You must use createUrl() or createAbsoluteUrl() as #Grimv01k recommends you. When in view or in controller you can do this by
$this->createUrl( 'foo/bar',array('id'=>321) )
Other ways:
Yii::app()->controller->createUrl('/baz/foo/bar'); // will use current controller
or
Yii::app()->createUrl('/baz/foo/bar')
Edited
So if you want
to unset a session when a user clicks on a icon
you can do this in following way.
echo CHtml::ajaxLink(
'click me to destroy session, mua-ha-ha',
Yii::app()->createUrl( '/session/destroy' ),
array(
'type' => 'post',
'dataType' => 'json',
'data' => array(
'foo' => 'bar',
),
'beforeSend' => 'js:function(){
console.log( $(this) );
return false;
}',
'success' => 'js:function(data){
console.log(data);
}',
)
);
in SessionController:
public function actionDestroy () {
if ( isset( $_POST['foo'] ) ) {
Yii::app()->session->destroy();
if ( Yii::app()->request->isAjaxRequest ) {
$response = array(
'status' => !Yii::app()->session->sessionID
) ;
echo CJSON::encode( (object) $response );
Yii::app()->end();
}
}
}

How to make ajax call in yii2?

In yii version 1.14 we used
CHtml::ajaxlink
for ajax call what about in yii2?
You can make an ajax link like
Html::a('Your Link name','controller/action', [
'title' => Yii::t('yii', 'Close'),
'onclick'=>"$('#close').dialog('open');//for jui dialog in my page
$.ajax({
type :'POST',
cache : false,
url : 'controller/action',
success : function(response) {
$('#close').html(response);
}
});return false;",
]);
From: http://www.yiiframework.com/wiki/665/overcoming-removal-of-client-helpers-e-g-ajaxlink-and-clientscript-in-yii-2-0/
You can easily create and combine all such client helpers for your
need into separate JS files. Use the new AssetBundle and AssetManager
functionality with the View object in Yii2, to manage these assets and
how they are loaded.
Alternatively, inline assets (JS/CSS) can be registered at runtime
from within the View. For example you can clearly simulate the
ajaxLink feature using a inline javascript. Its however recommended if
you can merge where possible, client code (JS/CSS) into separate
JS/CSS files and loaded through the AssetBundle. Note there is no more
need of a CClientScript anymore:
$script = <<< JS
$('#el').on('click', function(e) {
$.ajax({
url: '/path/to/action',
data: {id: '<id>', 'other': '<other>'},
success: function(data) {
// process data
}
});
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
$.get( "' . Url::toRoute('controller/action') . '", { item: $("#idoffield").val()} ) /* to send the parameter to controller*/
.done(function( data )
{
$( "#lists" ).html( data );
})
and give lists id for div
<div id="lists"></div>
for more visit https://youtu.be/it5oNLDNU44
<?=yii\helpers\Url::toRoute("site/signup")?>

Execute PHP Code via Ajax Call in drupal module

I was trying to convert this into a Drupal module so that I can check PHP code instantly on my site for debugging purposes. I saw this Firefox add on which allows you to execute PHP on the fly but admin log in is necessary, so far I did everything , have one form and set up ajax calls , but if I pass a string like:
preg_match($pat,$str,$matches);
print_r($matches);
How to execute this in backend?
EDIT
To load the form:
$items['localphp'] = array(
'page callback' => 'executePHP',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
function executePHP(){
$output = drupal_get_form('executePHP_form');
return $output;
}
Ajax callback function:
$items['runPHP'] = array(
'page callback' => 'getResult',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
function getResult(){
$code = $_POST['code'];
//I need help here how to execute $code i.e the php code and return back result
echo $code;
}
JS function
function executePHP(baseurl){
var code = $("#edit-code").val();
$.ajax({
type : "POST",
url : baseurl+'runPHP',
data : 'code='+code,
async : true,
cache : false,
success : function (res) {
$("#edit-result").html(res);
},
error : function (res) {
alert("error");
}
});
return false;
}
FYI, the Devel module has a feature that allows admins to run custom PHP code from their page. The Devel module has a block with a ton of features useful for debugging.
For a custom module, without seeing any of your other code, I can tell you what I have done to achieve AJAX in a Drupal module:
In JavaScript make an AJAX request to a url on your site. Add a menu item with the specified path inside of hook_menu() as 'type' => MENU_CALLBACK that points to a function in your module. This function should do all the processing you need, then return the results to JavaScript to do what you want with it there.

Insert PHP code into my page.xml

page.xml.php will not show any output, in firebug I can see the get response for page.xml.php with my class responsible for extracting the data isn't seeing the content as xml data
How can i get this to work?
index.php
// Load config file
$config = simplexml_load_file("resources/pinboard/config.xml.php");
page.xml.php
<?php header("Content-type: text/xml"); ?>
...
<module name="Weather" id="23">
<title>Weather</title>
<location><?php echo $_COOKIE['zip_code']; ?></location>
</module>
...
weather.php
...
protected $default_config = array(
'title' => 'Weather',
'refresh' => '200000', // Every 20 minutes
'location' => "Los+Angeles",
'format' => 'f'
);
...
site.js
...
$.ajax({
type: "GET",
url: "resources/pinboard/config.xml.php?" + new Date().getTime(),
dataType: "xml",
success: function(xml) {
// Parse config
$(xml).find('settings').children().each(function(test){
settings[$(this)[0].localName] = $(this).text();
});
// Call init (startup the picboard)
init();
}
});
...
Your loading your xml.php file with
$config = simplexml_load_file("resources/pinboard/config.xml.php");
But that would not return a parsed file, just the source. Now I don't know if your other xml.php files are loaded like that, -but you need to "go trough the webserver" for it to work.
The ajax call does seem correct though.
As suggested in the comments:
use more sensible application structure

Categories