joomla 2.5 ajax api - ajax

I would like to setup some little ajax support for my joomla page, in detail: I would like to send logging messages from the frontend to the backend via ajax and store them in database.
In drupal this can be done by adding a path and a callback inside a module, so how can this be achieved in joomla 2.5, so that there is an url like:
http://www.domain.com/log which leads to a function call?
Greetings..

The proper way would be to create a component to handle the call, but as you write most of the time it seems a bit overkill for just a module.
Another way would be to create a standalone php-file that uses the Joomla-library. This file could then easily be called from wherever you like. It's like a mini-version of Joomla with the advantage of having all libraries available:
define( 'DS', DIRECTORY_SEPARATOR );
if (!defined('JPATH_BASE')){
define('JPATH_BASE', '..'.DS.'..'.DS.'..');
}
define('JPATH_LIBRARIES', JPATH_BASE . DS . 'libraries');
require_once JPATH_LIBRARIES . DS . 'import.php';
$var = JRequest::getVar('my_var');
To access the DB-object, you would need to manually set the options to the DB-object since this file won't access the configuration files (you can program this of course).
$option = array(); //prevent problems
$option['driver']   = 'mysql';            // Database driver name
$option['host']     = 'db.myhost.com';    // Database host name
$option['user']     = 'myuser';       // User for database authentication
$option['password'] = 'mypass';   // Password for database authentication
$option['database'] = 'bigdatabase';      // Database name
$option['prefix']   = 'abc_';             // Database prefix (may be empty)
$db = & JDatabase::getInstance( $option );

Related

RuntimeException laravel 5.8 RuntimeException This driver does not support creating temporary URLs

RuntimeException This driver does not support creating temporary URLs.
I am trying to generating Temp Url for every request Laravel version 5.8 below code trying showing an error.
This driver does not support creating temporary URLs.
$url = "66.jpeg";
$url = Storage::disk('public')->url($url);
$url = Storage::disk('public')->temporaryUrl(
'66.jpeg', now()->addMinutes(5)
);
From my knowledge, temporaryUrl is a method used on a drivers such as s3 to create a temporary url for a privately stored asset.
If you would like to set a temporary url for a file, it may help to use Cache to temporarily store the path.
Cache can set a key/value for a set amount of time. A url can be create which links to an endpoint. Then endpoint can then be created which returns the contents of that file:
// Creating temp file index in cache
$image = '66.jpg';
Cache::put('/temp/' . $image, 300); // 5 minutes
Now in, for example, TempController.php (visiting http://example.com/temp/66.jpg):
public function show($image)
{
if (Cache::get('/temp/' . $image) && ! Storage::disk('public')->exists($image)) {
// not in cache or do not exist, maybe redirect...
};
return Storage::disk('public')->get($image);
}
This is a proof of concept however I hope this helps.

Error 404 WP Ajax Request

I was working on creating a WP plugin that will load other plugins only on specific URL. These plugins are deactivate in WP admin plugins, and are only loaded when a specific page is accessed.
Within my plugin's Class construct function:
$uri = $_SERVER['REQUEST_URI'];
$exp = explode('/', $uri);
$uri = $exp[2];
$options = get_option( $this->plugin_name );
$key = array_search( '/'.$uri.'/', array_column($options, 'url') );
$plugin_dir = $options[$key]['plugin']; // this prints plugin file directory ex. /MyPlugin/myplugin.php
include( WP_PLUGIN_DIR . $plugin_dir);
Above code loads the plugin on specific URL/page. Meaning the variable $plugin_dir grabbed the correct directory. BUT, problem occur when there's an AJAX request from that plugin. Ex. when i try to delete an item using ajax request, it returns Error 404 Bad request.
Weird part is, almost same code above, but this time, i manually assign the plugin directory to a variable: ex.
$uri = $_SERVER['REQUEST_URI'];
$exp = explode('/', $uri);
$uri = $exp[2];
$options = get_option( $this->plugin_name );
$key = array_search( '/'.$uri.'/', array_column($options, 'url') );
$plugin_dir = '/MyPlugin/myplugin.php'; // manually place the plugin file dir
//same output as $plugin_dir = $options[$key]['plugin'];
include( WP_PLUGIN_DIR . $plugin_dir);
But this time, plugin works really well. No Ajax bad request error.
What could be the possible explanation for this? Is there any solution about this issue, so that i can dynamically get the plugin file directory from wp options based on the Request URI.
Also, another issue. Instead of REQUEST URI, i wanted to get the POST/PAGE ID instead, but everything returns NULL/empty. Still inside the construct function, i tried different approach to get the page ID:
global $post;
var_dump($post->ID); //returns NULL
global $wp_query;
var_dump($wp_query->post->ID); //returns NULL
echo get_the_ID(); //returns empty/NULL
Is there a way how to properly get the POST/PAGE details, or even just the ID?
Thank you.

configuring dynamic url's in router

I'm using Codeigniter. Basically what I want is to remove the Controller name (Home) from the url.
Those urls look like:
http://localhost/mechanicly/Home
http://localhost/mechanicly/Home/about
http://localhost/mechanicly/Home/contactus
now there are two ways I can remove the Home controller:
static definition of every url inside route:
$route['about'] = "Home/about";
$route['contactus'] = "Home/contactus";
I can use call backs in routes in Codeigniter:
$route['(.+)'] = function ( $param ) {
if( strpos( $param, "Admin" ) !== false ) {
echo $param;
return "Admin/".$param;
}
else{
echo $param;
return "Home/".$param;
}
};
this logic is much better as it is generic and I don't have to create new routes every time for new method inside the controller.
It is working fine for the client controller which is Home but I have another controller named as Admin and I want to redirect Admin requests to the Admin controller and Home request to the Home Controller.
Why does above code work fine for the Home controller but returns
not found
when I validate for the Admin controller?
I am using CI version 3.x
If you really want to get crazy, you could parse the methods from the controller file and programatically create the "static" approach.
Pseudo code here
$controller_file_contents = file_get_contents('path/to/controller.php');
$controller_methods = function_that_parses_methods_from_file($controller_file_contents);
foreach ($controller_methods as $controller_method) {
$route[$controller_method] = "Home/" . $controller_method;
}
How function_that_parses_methods_from_file works is probably gonna involve a regex, something like function \w+. If you go with this approach, try to keep the controller as small as possible by offloading as much logic as possible into models, which is often a good idea anyways. That way the performance impact in the router is as small as possible.
Alternatively, you may be able to parse the controller using get_class_methods if you can figure out how to load the controller into memory inside the router without conflicting when you need to load the controller using the router or causing too much performance issues.
Pretty goofy, but every method you create in that controller will automatically create a route.
you can create your menu(url´s) from db like
tbl_menu tbl_level
---------- -------------
id id
fk_level level
name dateUP
dateUP active
active
In your controllers you need to call the correct menu by session or wherever you want
then you can has this in your route.php
$route['(.+)'] = 'int_rout/routing/' . json_encode($1);
in your controller Int_rout.php
public function routing ( $param ) {
$routing = json_decode($param);
$routing = explode('/', $routing);
//$menu -> get menu from model
foreach($menu as $item){
if($routing[0] === $item->name){
//$level -> get level from model
$redirect = $level->level;
}
}
//the final redirect will be like
//admin/user or admin/user/12
//public/us
$params = ( empty($routing[1])) ? '' : '/' . $routing[1];
redirect($redirect . '/' . $routing[0] . $params, 'refresh');
}

Send Data From html5 app to database by ajax and php

i have start a new application html5 and i need to send from that app the info user_points to the database i have the code that send a fixed amount points.
But Now I need to change the php code to receive ajax request to update is points on database From My html5 app.
what i can change to this php code to receive the ajax variable user_points and store in database?
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
// Retrieve data from database
$result=mysql_query($sql);
//$sql = mysql_query("UPDATE `users` SET points=`points`+5 WHERE user_id='".$_SESSION['user']."'");
$user_id = mysql_real_escape_string($_SESSION['user']);
$sql = mysql_query("UPDATE `users` SET user_points = user_points +'user_points' WHERE user_id = " . $_SESSION['user']);
// close MySQL connection
mysql_close();
?>
assume your php script is called run.php
and assume run.php is called via ajax like this http://yourserver/run.php?user_points=10&userid=12&sessiontan=8162836zqwizß182402834080oio
your script run.php would need to look like this:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_GET['userid']) and isset($_GET['user_points'] and isset($_GET['sessionpin']))) {
$res=mysql_query("SELECT userid FROM sessiontans WHERE user_id=x".dechex($_GET['userid'])" and sessiontan=x".dechex($_GET['sessiontan']));
if($row = mysql_fetch_array($res)) {
$sql = mysql_query("UPDATE `users` SET user_points = user_points + x".dechex($_GET['user_points'])." WHERE user_id = x" . dechex($_GET['userid']));
}
}
// close MySQL connection
mysql_close();
?>
As far as I am aware the session context is not available in ajax called scripts. So security wise that needs to 'simulated' via sessiontans or similar mechanisms. I assumed now, you would follow a sessiontan approach. A session tan be created in your app as soon as the user logs and is via time stamps only valid for a tiny time frame (a couple of minutes/hours). A sessiontan would need to be different from session-IDs.
I personally would add more sophisticated checks on the user-points to make sure that the those are not tricked... Anyway that is more on the 'game logic' side and would require a lot more insight on what this is all about.
Also in terms of performance tuning both statements could become part of a multi query: http://php.net/manual/de/mysqli.multi-query.php
Again this is advanced programming tactics and superexceeds the scope of your question.

Codeigniter loading library after session is set

I am using codeigniter with sqlite and I have created a new library for connecting the sqlite database. The sqlite database will connect only if the session is set.
LIBRARY (userdb)
$CI =& get_instance();
if( $CI->session->userdata('user') ){
$userId = $CI->session->userdata('user');
$this->conDb = new PDO("sqlite:" . BASEPATH . "sqlitedb/" . $userId . "/data.db");
}else{
$userId = '';
}
And I execute queries by using $query = $this->userdb->query($sql);
It works fine but the problem is that query only works if the page is refreshed after session is created otherwise it returns Call to a member function query() on a non-object error.
CONTROLLER
$sessiondata = array('user' => $userid);
$this->session->set_userdata($sessiondata);
$insert = $this->user_model->insert($data);
All this seems legit, if you set your userdata while the page/controller is loading it means that the librairies and other assets have been loaded already. So when your userdb library is loaded there is no sessions set yet.
You have two ways to fix this : Try to Load your library after loading your controller but for a db library this would be better to be in your config file so that it is auto loaded.
The other way would be to reload or redirect your current PAGE after the session isset. So that you can use your db library
Hope that helps You
NwK

Resources