How to give source : path to jQuery autocomplete from Codeigniter - php

I have used jQuery auto complete on my Codeigniter application. But it's not working due to source path is broken.
This is my code:
jQuery(document).ready(function(){
$('.zipsearch').autocomplete({
source:'jQueryAutocompleteRelatedFields.php',
minLength:2,
select:function(evt, ui)
{
// when a zipcode is selected, populate related fields in this form
this.form.city.value = ui.item.city;
this.form.state.value = ui.item.state;
}
});
});
Currently file jQueryAutocompleteRelatedFields.php is on the following file path:
www\CI\application\views\search\jQueryAutocompleteRelatedFields.php
localhost\CI\index.php\search\searchItem
Is my browser path
How can I give the source?
SearchITem is function which coming under search controller,
Update : jQueryAutocompleteRelatedFields.php
<?php
class DB
{
const DATABASE = 'inventory';
const HOST = '127.0.0.1';
const USERNAME = 'root';
const PASSWORD = '';
static private $pdo;
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
private function __construct()
{
}
public function __clone()
{
throw new Exception('You may not clone the DB instance');
}
}
if (!isset($_REQUEST['term']))
{
die('([])');
}
$st = DB::singleton()
->prepare(
'select product_id, product_code, product_name ' .
'from tbl_product ' .
'where product_id like :product_id ' .
'order by product_id asc ' .
'limit 0,10');
$searchZip = $_REQUEST['term'] . '%';
$st->bindParam(':product_id', $searchZip, PDO::PARAM_STR);
$data = array();
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$data[] = array(
'value' => $row->product_id ,
'city' => $row->product_code ,
'state' => $row->product_name
);
}
}
echo json_encode($data);
flush();

You should use the browser path with forward slashes.
source: 'localhost/CI/index.php/search/searchitem',
You will have an issue moving this to a real web server though because you will want to use a relative path. I highly recommend setting up your local environment to be as similar as possible to the web server.
EDIT:
In CodeIgniter add the following code to your Search controller:
public function fetchList(){
// I assume your view is outputting an array ready to be encoded with JSON?
return json_encode($this->load->view('search/jQueryAutocompleteRelatedFields.php', array(), true));
// Try this if the code above doesn't work
return json_encode(array('item1','item2','item3','item4'));
}
Now point the AJAX source like this:
source: 'localhost/CI/index.php/search/fetchList',

Related

Why is include('../myscript.php') causing an error?

I've been trying to debug my PHP script and I've narrowed down the problem to the line
include "../classes.php";
at the top of my file team_manager.php which is where you see it below.
themes
my_theme
js
management
team_manager.php
project_manager.php
classes.php
footer.php
functions.php
Am I not doing the path correctly? Or could it be something wrong with the contents of classes.php? If it could be a problem with the file being included, below is the file, and let me know if anything immediately stands out as wrong.
<?php
final class MySqlInfo
{
const DBNAME = 'somedb';
const USER = 'someuser';
const PSSWD = 'somepassword';
const TEAMTABLENAME = 'sometablename';
public function getUser ( )
{
return self::USER;
}
public function getPassword ( )
{
return self::PSSWD;
}
}
final class MethodResult
{
public $succeeded;
public $message;
public MethodResult ( $succeededInit = NULL, $messageInit = NULL )
{
this->$succeeded = $succeededInit;
this->$message = $messageInit;
}
}
final class MySite
{
const ROOTURL = 'http://asite.com/subsite';
function getRootUrl()
{
return self::ROOTURL;
}
}
final class TeamManager
{
private $dbcon;
public function TeamManager ( )
{
$dbcon = mysqli_connect('localhost', MySqlInfo.getUser(), MySqlInfo::getPassword());
$dbcon->select_db(MySqlInfo::DBNAME);
// need to add error handling here
}
final public class TeamMember
{
public $name; // team member name
public $title; // team member title
public $bio; // team member bio
public $sord; // team member sort order
public $picfn; // team member profile picture file name
}
public function addMember ( TeamMember $M )
{
if ($this->$dbcon->connect_error)
{
return new MethodResult(false, 'Not connected to database');
}
$q = "INSERT INTO " . MySqlInfo::TEAMTABLENAME . " (" . implode( ',' array($M->name, $M->title, $M->bio, $M->sord, $M->picfn) ) . ") VALUES ('" . implode('\',\'', array($_POST['fullname'], $_POST['title'], $_POST['bio'], $_POST['sord'], $targetFileName)) . "')";
// ^ query for inserting member M to the database
if (!mysqli_query(this->$dbcon, $q))
{
return new MethodResult(false, 'Query to insert new team member failed');
}
return new MethodResult(true, 'Successfully added new member' . $M->name);
}
}
?>
include() might cause an error in case it can't find a file to be included. It's that simple. So you have to make sure that file exists before you include it. Also, never use relative paths like ../script.php, as they introduce a number of issues. And one major issue is that, some hosting providers don't allow relative paths due to security reasons.
So to make sure the file can be included, simply do the check for its existence:
<?php
// dirname(__FILE__) returns an absolute path of the current script
// which is being executed
$file = dirname(__FILE__) . '/script.php';
if (is_file($file)) {
include($file);
} else {
echo 'File does not exist';
}
Also, I see that you write code as an old-school. You might want to take a look at PSR-FIG standards.

Custom PHP SessionHandler class Write issue

I'm creating my own custom SessionHandler to store my session information in a postgresql 9.3 database and I'm having a problem where the session data passed to the write() method isn't being written to the database, but the session name is??
Things that I know for a fact
My custom class is handling the sessions when session_start() is called - as tested with echoing output from the various methods and no session files are being created in /tmp
The $session_data arg in write() contains the proper serialized string as shown by echoing the contents in the write() method.
$session_name is being written to the database just fine and so is a BLANK serialized string a:0:{}.
Things I'm confused about:
Echoing the contents of $_SESSION['test_var1'] shows the correct value stored, even if read() is empty or returning no value??
If the session name is saved in the DB just fine, why isn't the session data?
Server Configuration
OS: Gentoo
Database: Postgresql 9.3
Web Server: NGINX 1.7.6
PHP 5.5.18 connected to NGINX via FPM
PHP ini session settings
session.save_handler = user
session.use_strict_mode = 1
session.use_cookies = 1
session.cookie_secure = 1
session.use_only_cookies = 1
session.name = _g
session.auto_start = 0
session.serialize_handler = php_serialize
class SessionManagement implements SessionHandlerInterface {
private $_id = '';
private $_link = null;
public function __construct() {
session_set_save_handler(
[$this, 'open'],
[$this, 'close'],
[$this, 'read'],
[$this, 'write'],
[$this, 'destroy'],
[$this, 'gc']
);
}
public function open($save_path, $session_id) {
echo 'open called<br/>';
$this->_id = $session_id;
$this->_link = new PDO('pgsql:host=' . $_SERVER['DB_HOST'] . ';dbname=' . $_SERVER['DB_DB'],
$_SERVER['DB_USER'],
$_SERVER['DB_PASS']);
}
public function close() {
echo 'close called<br/>';
}
public function destroy($session_id) {
echo 'destroying '.$session_id, '<br/>';
}
public function gc($maxlifetime) {
echo 'GC called<br/>';
}
public function read($session_name) {
$name = $this->_id.'_'.$session_name;
$sql = 'SELECT session_data FROM sessions WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
} else {
return false;
}
} else {
return false;
}
return '';
}
public function write($session_name, $session_data) {
echo 'Session data: '.$session_data.'<br/>';
$name = $this->_id . '_' . $session_name;
$data = $session_data;
$sql = "SELECT 1 FROM sessions WHERE session_name = :name";
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
if ($rel->rowCount()) {
echo 'Updating...<br/>';
$sql = 'UPDATE sessions SET session_data = :data WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Update success...<br/>';
} else {
echo 'Update failed...<br/>';
var_dump($rel->errorInfo());
}
}
} else {
echo 'Inserting...<br/>';
$sql = 'INSERT INTO sessions (session_name, session_data) ';
$sql .= 'VALUES(:name, :data)';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Insert success...<br/>';
} else {
echo 'Insert failed...<br/>';
var_dump($rel->errorInfo());
}
}
}
}
}
}
}
Test code:
new SessionManagement();
session_start();
$_SESSION['test_var1'] = 'some test data';
session_write_close(); // Making sure writing is finished
echo $_SESSION['test_var1'];
Output via test page
open called
Session data: a:1:{s:9:"test_var1";s:14:"some test data";}
Inserting...
Insert success...
close called
some test data
Relevant database fields
session_name: _g_h8m64bsb7a72dpj56vgojn6f4k3ncdf97leihcqfupg2qtvpbo20
session_data: a:0:{}
I'm not sure if this is a database issue or a PHP issue. I've been messing with this for a few days now and decided it was time to ask the community. Hopefully someone has some insight as to what the problem is.
I think you must initialize PDO object outside of the Open function handler and the class itself
try to access to your PDO Object with a Global value or through a static variable.
This is my implementation with MYSQL for my project :
class Core_DB_SessionHandler implements SessionHandlerInterface
{
protected $options = array(); // Options de la session
protected static $db = NULL; // Acceder a la BDD
public function __construct($options, $pdo) {
$this->options = $options;
self::$db = $pdo;
}
public function open($savePath, $sessionName) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
public function close() {
$this->gc(ini_get('session.gc_maxlifetime'));
}
public function read($id) {
$now = time();
$stmt = self::$db->query("SELECT data FROM tbl_sessions WHERE sid = '$id AND expire < '$now'");
$result = $stmt->fetchColumn();
return $result;
}
public function write($id, $data) {
if (array_key_exists('TIMEOUT', $_SESSION)) {
$newExp = $_SESSION['TIMEOUT'];
}
else {
$newExp = time() + $this->options['time_limiter'];
}
try {
$req = self::$db->prepare('INSERT INTO tbl_sessions (sid, data, expire) VALUES (:sid, :data, :expire)
ON DUPLICATE KEY UPDATE data = :data, expire = :expire');
$vals = array('sid' => $id, 'data' => $data, 'expire' => $newExp);
$req->execute($vals);
return TRUE;
}
catch (PDOException $e) {
throw new Core_Exception(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
}
}
public function destroy($id) {
$stmt = self::$db->prepare("DELETE FROM tbl_sessions WHERE sid = '{1}'");
$stmt->execute(array($id));
//return ($stmt->rowCount() === 1) ? true : false;
return TRUE;
}
public function gc($maxlifetime) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
}
and i initialize handler like this :
$handler = new Core_DB_SessionHandler($MyOptions, $MyPDO);
if (PHP5) {
if (!session_set_save_handler($handler, TRUE)) {
throw new Core_Exception('Erreur lors de l\'init des sessions !');
}
}
nb : In your Table structure don't use autoincrement for ID
Well, I've solved my problem, but it's hard to say if this fix was actually the problem in the first place.
In the read method, I changed the follow:
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
to
$data $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
return $data;
After this the session was writing $session_data to the database without any problem. That's all well and dandy, but it doesn't explain why it didn't work in the first place. I mainly say this because upon switching the statement back everything continued to work. As in, I can't reproduce the issue now. So it's hard for me to even say that this was the problem in the first place.
Hopefully this helps someone. I've been unable to find more information about it, but it something does show up I'll be sure to add it here.

saving data from joomla frontend

I was looking for a solution as to how to save data from joomla frontend. I came across the following code for controller and model which works perfectly. But I was looking for a standard practice like its done in the back end using jform, jtable etc ... In the following code (inside model), the saving technique do not look so appealing. And I am totally without any idea how the server side validations is implemented.
It might be confusing, so i would like to reiterate that in the backend we don't even have to write the add or save or update function, it is automatically handled by the core classes with both client and server side validation. So i was looking for something like that.
Controller
<?php
// No direct access.
defined('_JEXEC') or die;
// Include dependancy of the main controllerform class
jimport('joomla.application.component.controllerform');
class JobsControllerRegistration extends JControllerForm
{
public function getModel($name = 'Registration', $prefix = 'JobsModel', $config = array('ignore_request' => true))
{
return parent::getModel($name, $prefix, array('ignore_request' => false));
}
public function submit()
{
// Check for request forgeries.
JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('Registration');
// Get the data from the form POST
$data = JRequest::getVar('jform', array(), 'post', 'array');
$form = $model->getForm();
if (!$form) {
JError::raiseError(500, $model->getError());
return false;
}
// Now update the loaded data to the database via a function in the model
$upditem = $model->updItem($data);
// check if ok and display appropriate message. This can also have a redirect if desired.
if ($upditem) {
echo "<h2>Joining with us is successfully saved.</h2>";
} else {
echo "<h2>Joining with us faild.</h2>";
}
return true;
}
}
Model
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// Include dependancy of the main model form
jimport('joomla.application.component.modelform');
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
// Include dependancy of the dispatcher
jimport('joomla.event.dispatcher');
/**
* HelloWorld Model
*/
class JobsModelRegistration extends JModelForm
{
/**
* #var object item
*/
protected $item;
/**
* Get the data for a new qualification
*/
public function getForm($data = array(), $loadData = true)
{
$app = JFactory::getApplication('site');
// Get the form.
$form = $this->loadForm('com_jobs.registration', 'registration', array('control' => 'jform', 'load_data' => true),true);
if (empty($form)) {
return false;
}
return $form;
}
//Nwely added method for saving data
public function updItem($data)
{
// set the variables from the passed data
$fname = $data['fname'];
$lname = $data['lname'];
$age = $data['age'];
$city = $data['city'];
$telephone = $data['telephone'];
$email = $data['email'];
$comments = $data['comments'];
// set the data into a query to update the record
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->clear();
$db =& JFactory::getDBO();
$query = "INSERT INTO #__joinwithus ( `id`, `firstname`, `lastname`, `age`, `city`, `telephone`, `email`, `comment`)
VALUES (NULL,'" . $fname . "','" . $lname . "','" . $age . "','" . $city . "','" . $email . "','" . $telephone . "','" . $comments . "')";
$db->setQuery((string)$query);
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
} else {
return true;
}
}
}
Can somebody kindly point me to a good tutorial or share me a component which deals with form in the frontend with joomla 2.5.
use the following code in your model
$data = $app->input->getArray($_POST);
$query = $db->getQuery(true);
You should be able to use jcontrollerform's methods directly, instead of writing your own submit()-method (and updItem()) like you do. I describe something similar here. This means you display your form the usual way using jform, and use action="index.php?option=com_jobs&task=save&view=registration&id=whateverid"
This way jcontrollerform->save() is used, which in turn calls your model's save(). (Hmmm, this probably means your model should extend JModelAdmin instead of JModelForm, to include the relevant methods. ) This will run all the necessary validation checks etc.
You might need to register paths for the model, table and form that you want to be using, like I do in the link.
You need to include the id in the url parameters if you edit existing data, because the jform[id] - parameter will be ignored.
Sorry I dont have any good tutorial or whatever for you, hope this helps.

Cannot use object of type lang as array

I found a free PHP admin system script online which I have setup but can not get working.
I keep getting this error "Cannot use object of type lang as array"
and i'm not sure what this means.
The line of code that the error is on is part of a class which is here:
class lang {
public function __construct( $lang = false, $URL = '' ) {
}
private function storeAllowedLanguages() {
}
private function setLanguage($lang) {
}
public static function createButtons($ismobile) {
}
public static function translate($key, $ucfirst=false) {
if( !isset($_SESSION['LANG']) ) {
$DB = new db;
$sql = '
SELECT `key`, `value`
FROM `_adminlang`
WHERE `lang` = "en"
';
$res = $DB->fetch( $sql );
foreach($res as $rec) {
$_SESSION['LANG'][$rec['key']] = $rec['value'];
}
}
return isset($_SESSION['LANG'][$key]) ? $_SESSION['LANG'][$key] : ucfirst(str_replace('_', ' ', strtolower($key)));
}
}
and the actual line is :
return isset($_SESSION['LANG'][$key]) ? $_SESSION['LANG'][$key] : ucfirst(str_replace('_', ' ', strtolower($key)));
could someone help me out with this error please im very stuck
$_SESSION['LANG'] is most likely a object.. try
$_SESSION['LANG']->$key

PHP including external files which use class fields from base file

Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.

Categories