Search from different table in yii - javascript

I am new to Yii. I have basically two tables for computation. TABLE:Mst_customers=> model name = masterCustomers ,TABLE:mst_nimsoft_host=> model name = NimsoftHost. I have a drop-down in my view, where it asks for Search by customer name or by host name. I have default search by customer name. Below that I have a text field with AJAX validation. the operation is that when I enter three letters, it must suggest customers name similar to that. and if I select search by host name in drop down and if I enter three letters/numbers it must check for similar host name in mst_nimsoft_host table, I have given my code here
My controller:
<?php
class NimsoftController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/ticket_console';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','nimsoftCustomers','Search','Details','UploadCustomers','StaticCi','city2','Customers','CiLink','LoadCustType'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate($id)
{
$model=new NimsoftHost;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$cust_id=$id;
$criteria = new CDbCriteria;
$cust_name = MasterCustomers::model()->findByPk($cust_id);
if(isset($_POST['NimsoftHost']))
{
$model->attributes=$_POST['NimsoftHost'];
$model->host_customer_id=$id;
if($model->save())
{
$this->redirect(array('view','id'=>$model->host_id));
}
}
$this->render('create',array(
'model'=>$model,'cust_id'=>$cust_id,'cust_name'=>$cust_name->cust_name
));
}
public function actionLoadCustType(){
$customer_id = $_POST['NimsoftHost']['host_customer_id'];
//$customer_id = 3;
// customer type
$custDetails = masterCustomers::model()->findByPk($customer_id);
$customer_type = $custDetails->cust_type;
// get customer service details
$criteria = new CDbCriteria;
$serviceDetails = masterCustomerServices::model()->findAllByAttributes(array('cust_id'=>$customer_id,'i_type'=>'im'));
//$serviceArr = array(array('label'=>'Please Service','value'=>''));
//$slaArr = array(array('label'=>'Please Select SLA','value'=>''));
//$blankServices = array();
//$srtypeArr = array(array('label'=>'Select SR Type','value'=>''));
foreach($serviceDetails as $val){
// get sla name
$criteria = new CDbCriteria;
$sla = masterSla::model()->findByPk($val->sla_id);
$slaArr[] = array(
'label' => $sla->sla_name,
'value' => $val->sla_id,
);
/*// get service type
$criteria = new CDbCriteria;
$services = masterServiceType::model()->findByPk($val->service_type_id);
$blankServices[] = $services->service_type_id;
$serviceArr[] = array(
'label' => $services->service_type_name,
'value' => $services->service_type_id,
);*/
//$serviceArr[$val->service_type_id] = $services->service_type_name;
}
// customer type
$custTypeDetails = MasterCustomerType::model()->findByPk($customer_type);
/* // get sr types
$criteria = new CDbCriteria;
$criteria->addCondition("i_type = 'im'", 'AND');
$criteria->addInCondition('sr_service_type_id',$blankServices);
$srArr = masterSrTypes::model()->findAll($criteria);
foreach($srArr as $sr){
$srtypeArr[] = array(
'label' => $sr->sr_type_name,
'value' => $sr->sr_type_id,
);
}*/
echo json_encode(array('cust_type'=>$custTypeDetails->cust_type_name,
'customerid'=>md5($customer_id),
//'services'=>$serviceArr,
//'srtypes'=>$srtypeArr,
'slas'=>$slaArr,
'sfdc'=>$custDetails->cust_sfdc_id,
'accountid'=>$custDetails->cust_account_id));
}
public function actionDetails($id)
{
$this->layout = 'iframe';
$custid=$id;
if(isset($custid) && $custid != ''){
$criteria = new CDbCriteria;
$criteria->condition = "md5(cust_id) = '$custid'";
$details = masterCustomers::model()->findAll($criteria);
// get service & sla Details
$criteria = new CDbCriteria;
$criteria->condition = "md5(cust_id) = '$custid'";
$sdetails = masterCustomerServices::model()->findAll($criteria);
//get host details
$criteria = new CDbCriteria;
$criteria->condition = "md5(host_customer_id) = '$custid'";
$hostdetails = NimsoftHost::model()->findAll($criteria);
// get contact details
$criteria = new CDbCriteria;
$criteria->condition = "md5(cust_id) = '$custid'";
$criteria->with = array('contactCategory');
$contactDetails = masterCustomersContacts::model()->findAll($criteria);
$this->render('details',array('customer'=>$details,'service'=>$sdetails,'contact'=>$contactDetails,'host'=>$hostdetails));
}
}
public function actionCiLink($action=''){
$this->layout = 'iframe';
if(isset($action) && isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$cis = Yii::app()->user->getState("ci_relations");
$temp = array();
if(!empty($cis)){
foreach($cis as $val){
if($id != $val){
$temp[] = $val;
}
}
Yii::app()->user->setState("ci_relations",$temp);
}
echo $this->renderPartial('_static_ci_display',array('citems'=>Yii::app()->user->getState("ci_relations")));
exit;
}
if(isset($_REQUEST['checkCI'])){
$ci = $_REQUEST['checkCI'];
if(Yii::app()->user->hasState("ci_relations")){
$existing = Yii::app()->user->getState("ci_relations");
foreach($ci as $new){
$existing[] = $new;
}
Yii::app()->user->setState("ci_relations", array_unique($existing));
}else{
Yii::app()->user->setState("ci_relations",$ci);
}
echo '
<div style="font-size:12px;font-family:Arial;color:#CCC;">CI Relation added successfully.</div>
<script>
var jQuery = parent.jQuery;
setTimeout(function () {
try {
jQuery("#ci_items", window.parent.document).empty().html("please wait loading...");
jQuery("#ci_items", window.parent.document).empty().load("'.$this->createUrl('itsmIncidents/staticCi').'");
parent.window.hs.getExpander().close();
} catch (e) {}
}, 500);
</script>
';
exit;
}
$model = new CmdbMaster('customsearch');
$model->unsetAttributes(); // clear any default values
if(Yii::app()->request->isAjaxRequest){
$inc = $_REQUEST['itsmIncidents']['inc_number'];
if (isset($_GET['CmdbMaster'])) {
$model->attributes = $_GET['CmdbMaster'];
}
$this->renderPartial('_ci_form_grid_json', array(
'model' => $model,
'inc'=> $inc,
'pages' => 10
));
exit;
}
$this->render('_static_ci_form');
}
public function actionStaticCi(){
echo $this->renderPartial('_static_ci_display',array('citems'=>Yii::app()->user->getState("ci_relations")));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['NimsoftHost']))
{
$model->attributes=$_POST['NimsoftHost'];
if($model->save())
$this->redirect(array('view','id'=>$model->host_id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$user = Yii::app()->db->createCommand()
->select('cust_name')
->from('mst_customers')
->queryAll();
$dataProvider=new CActiveDataProvider('NimsoftHost');
$model = new NimsoftHost();
$this->render('sample',array(
'dataProvider'=>$dataProvider,
'user' => $user,
'model'=>$model,
));
}
public function actionCustomers(){
//header('content-type: application/json; charset=utf-8');
$select= $_GET['select'];
$str = $_GET['q'];
if($select=='Customer_name')
{
$criteria = new CDbCriteria();
$criteria->condition = "( cust_name like '%$str%')";
$models = masterCustomers::model()->findall($criteria);
}
else
{
$criteria = new CDbCriteria();
$criteria->condition = "( host_name like '%$str%')";
$models = NimsoftHost::model()->findall($criteria);
}
$result = array();
foreach ($models AS $groups)
{
if($groups->cust_account_id != ''){
$acc = ' ( '.$groups->cust_account_id.' ) ';
}
$result['details'][] = array(
'id' => $groups->cust_id,
'name' => $groups->cust_name.$acc,
);
}
echo $_GET['callback'] . "(";
echo CJSON::encode($result);
echo ")";
}
public function actionUploadCustomers()
{
$this->layout = 'iframe';
$model = new NimsoftHost;
if(isset($_POST['NimsoftHost'])){
$sfile = CUploadedFile::getInstance($model,'upload_file');
$path = $sfile->tempName;
$handle = fopen($path,"r");
if ($handle) {
$flag = true;
while(($line = fgetcsv($handle, 1000, ",")) != FALSE) {
if($flag) { $flag = false; continue; } // ignore first line
$model = new NimsoftHost;
$model->host_name = $hostname = trim($line[0]);
$model->host_serviceid = $host_serviceid = $line[1];
$model->host_customer_id= $host_customer_id = $line[2];
$user = Yii::app()->db->createCommand()
->select('cust_id')
->from('mst_customers')
->where('cust_name=:cust_name', array(':cust_name'=>$model->host_customer_id))
->queryRow();
$model->host_customer_id=$user['cust_id'];
if($model->validate() && $model->host_name != ''){
$model->save();
echo "Uploaded successfully";
}
else {
echo "ALREADY PRESENT";
}
}
}
fclose($handle);
exit;
}
$this->render('_upload_file',array('model'=>$model));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new NimsoftHost('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['NimsoftHost']))
$model->attributes=$_GET['NimsoftHost'];
$this->render('admin',array(
'model'=>$model,
));
}
public function actionSearch($id){
echo $cust_id=$id;
die();
$criteria = new CDbCriteria();
$criteria->condition = "md5(host_customer_id) = '$cust_id'";
$details = NimsoftHost::model()->find($criteria);
/*if($details)
{
$criteria = new CDbCriteria();
$criteria->condition = "md5(cust_id) = '$id'";
$details = MasterCustomers::model()->find($criteria);
$details=$details->cust_id;
}*/
$dataProvider=new CActiveDataProvider('NimsoftHost',array(
'criteria' => $criteria,));
$model = new NimsoftHost();
$this->render('index',array(
'dataProvider'=>$dataProvider,'details'=>$details));
/*$this->layout = 'ticket_console';
$model = new itsmIncidents('search');
$model->unsetAttributes();
// Groups details
$criteria = new CDbCriteria;
$arrGrp = masterGroups::model()->findall($criteria);
$arr = array();
foreach($arrGrp as $e)
{
$arr[$e->group_id]=$e->group_name;
}
$arrGrp=$arr;
// severity types details
$criteria = new CDbCriteria;
$arrSvr = masterSeverityType::model()->findall($criteria);
$arr = array();
$arr['']='Select Severity';
foreach($arrSvr as $e)
{
$arr[$e->severity_type_id]=$e->severity_type_name;
}
$arrSvr=$arr;
if(isset($_GET['itsmIncidents']))
$model->attributes=$_GET['itsmIncidents'];
if(Yii::app()->request->isAjaxRequest){
$this->renderPartial('_my_ticket_grid_json',array('dataProvider'=>$model->search()));
}else{
$this->render('_mysearch',array(
'model'=>$model,
'assgroup'=>$arrGrp,
'sevArr'=>$arrSvr,
));
}*/
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return NimsoftHost the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=NimsoftHost::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param NimsoftHost $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='nimsoft-host-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
My view:
<div id="content">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'nimsoft-host-form',
//'enableAjaxValidation'=>true,
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => true, // allow client validation for every field
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<div style="float:left;padding-left:20px;">
<select name="search_by" size="1" onchange="javascript:onchange_action()" >
<option value="Customer_name" selected>Customer Name</option>
<option value="Host_name" >Host Name</option>
</select>
<?php echo $form->labelEx($model,'host_customer_id'); ?>
<?php
$variable=$_POST['search_by'];
echo $form->textField($model,'host_customer_id',array('style'=>'width:420px;'));
$this->widget('ext.select2.ESelect2', array(
'selector' => '#NimsoftHost_host_customer_id',
'options' => array(
'allowClear'=>false,
'placeholder' => 'Search Customers',
'minimumInputLength' => 3,
'quietMillis'=>100,
'ajax' => array(
'url' => Yii::app()->createUrl('Nimsoft/customers/'),
'dataType' => 'jsonp',
'data' => 'js: function('.$variable.',term,page) {
return {
select:'.$variable.'
q: term,
//ctype: $("#itsmIncidents_cloudcustomer input:radio:checked").val(),
page_limit: 10,
};
}',
'results' => 'js: function(data,page){
return {results: data.details};
}',
),
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
),
));
?>
<div style="float:right">
<?php
echo CHtml::link('Manage Hosts', array('/Nimsoft/Search'), array(
//'onclick'=>'return hs.htmlExpand(this, { objectType: "iframe", wrapperClassName: "full-size",height:500, align: "center" } )',
'class'=>'btn btn-block btn-success',
'style'=>'width:150px;display:none;',
'id'=>'search_details_pop',
));
?>
</div>
</div>
</div>
<script>
function onchange_action()
{
var e=document.getElementsByName("search_by")[0];
alert("the value of the option here is "+e.value);
}
$("#NimsoftHost_host_customer_id").on("change", function(e) {
<?php echo CHtml::ajax(array(
'url'=>array('Nimsoft/loadCustType'),
'data'=> "js:{'NimsoftHost[host_customer_id]':e.val}",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
// search customer host details
$('#search_details_pop').css('display','block');
$('#search_details_pop').attr('href', 'Nimsoft/search/id/'+data.customerid);
} ",
))?>;
})
</script>
<?php $this->endWidget();?>
I am not able to perform the above requirement. please help me on this. Thanks in advance.

Here is a link for your question's answer.
I think that you can use autocomplete.
In the link, the answer will show the way to you. There is a actionAutoComplete function. edit it like,
// if $term first 3 character is numeric
$query = NimsoftHost::model()->findallbyattributes( array('somecolumn'=>$term));
// else
$query = masterCustomers::model()->findallbyattributes( array('somecolumn'=>$term));
$list = array();
foreach($query as $q){
$data['value']= $q['id'];
$data['label']= $q['name'];
$list[]= $data;
unset($data);
}
echo json_encode($list);

Related

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

How to generate an excel file using js

I have a UI that shows a CRUD(create, read, update and delete) account of an employee. Now, I want to add a generate button that when its click, a window will pop-up that will show and ask if the following data in the grid lines under the UI are to be open or saved using the excel report.Also, I have already EXcelPhp library.
Here's my code for my 'actions.class.php':
public function executeLoadEmployeeList(sfWebRequest $request)
{
// $start = $request->getParameter('start') ? $request->getParameter('start'): 2;
// $limit = $request->getParameter('limit') ? $request->getParameter('limit'): 2;
$query = pg_escape_string($request->getParameter('query'));
$start = $request->getParameter('start');
$limit = $request->getParameter('limit');
if(isset($limit))
{
$page = $start / $limit;
$page ++;
}
else
$page = 1;
$criteria = Doctrine_Query::create();//what is the query?? is it select,inset,update,delete?
$criteria->select("(fname || ' ' || lname) AS fullname, department");
$criteria->from('Employees'); // Select * from profile
$criteria->orderBy('id'); // order by id
//print $criteria->getSqlQuery();
//die();
if($query!=null)
{
$criteria->where("(fname ilike '%$query%' or lname ilike '%$query%' or department ilike '%$query%')"); //where (uname ilike '%$query%' or status ilike '%$query%')
}
$allData = $criteria->fetchArray();
// print "<pre>";
// print_r($allData);
// die();
$this->pager = new sfDoctrinePager('Employees', 20); //what is sfdoctrine about? dont mind this.. this is a symphony built in class for pager
$this->pager->setQuery($criteria);
$this->pager->setPage($page);
$this->pager->init();//What is the purpose of this line? //initialize sfDoctrinePager
$result['data'] = $this->pager->getResults();
$result['totalCount'] = count($allData);
$result['limit'] = $limit;
$result['page'] = $page;
$result['query'] = $query;
die(json_encode($result));
}
public function executeAddEmployee(sfWebRequest $request)
{
try{
$fname = $request->getParameter('fname');
$lname = $request->getParameter('lname');
$department = $request->getParameter('department');
$Employee = new Employees();
$Employee->fname = $fname;
$Employee->lname = $lname;
$Employee->department = $department;
//save the data to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Added.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeDeleteEmployee(sfWebRequest $request)
{
try{
//what is Doctrine::getTable's purpose // to get the table profile
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', $request->getParameter('id')));
$Employee->delete();
$data = array("success"=> true, "data"=>"Employee record is Deleted.");
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeEditEmployee(sfWebRequest $request)
{
try{
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', array($request->getParameter('id'))));
$criteria = Doctrine_Query::create();
$criteria->select('fname,lname,department');
$criteria->from('Employees');
$criteria->where('id = ?', $request->getParameter('id'));//('id = ?', $request->getParameter('id') means... id = $request->getParameter('id')
$result = $criteria->fetchArray();
$record['fname'] = $Employee['fname'];
$record['lname'] = $Employee['lname'];
$record['department'] = $Employee['department'];
$data = array("success"=> true, "data"=>$record);
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeUpdateEmployee(sfWebRequest $request)
{
try{
$Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id')));
$Employee->fname = $request->getParameter('fname');
$Employee->lname = $request->getParameter('lname');
$Employee->department = $request->getParameter('department');
//save the update to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Successfully Updated.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeGenerateEmployee(sfWebRequest $request)
{
// ...
}**
What I've tried so far is setting only the generate button and there's no action yet. This is under my try.js:
var generateItem = new Ext.Action ({
text: 'Generate Excel Report',
width: 60,
enabled: true,
});
Could someone help me regarding this issue?
You can not generate an excel file without using a server side language / script. You can just prepare how it Will look and add some functions to make it functional like write, delete etc.
You can generate an Excel spreadsheet without any server side processing however you'll have a hellish time with browser support.
In theory you could generate an excel formatted file in js then simply do a window.open with the data URI.
for example here's a javascript generated image:
window.open('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC');
however.. it'll probably not be supported in most of the browsers for Excel data URIs:
here's another similar question:
Data URI used to export to CSV/Excel (no server-side request) : browser support/limitations?

I want to create advanced search using ajax codeigniter per categories

I am making a search function with codeigniter.
The search needs to show the search result per category, when I click the categories it will be show the real result (detail, with the image).
For the search I made a form:
Title:
Author:
Publisher:
Year Published
ISBN :
<btn submit>
if I submit it will show the URL like this:
http:readynew1.8/advancedsearch/search?advTitle=diktat&advAuthor=&advPublisher=&advYear=&advISBN=
===========================================
Search Result
==========================================
Book 6
Journal 4
The code is fine until here.
The problem is that when I click the category book I cant get the data that was sent from the input form.
If I use $this->input->get(); and send it as parameter to my function showdetails(Title,ISBN);
the parameter cant be null, and also I cant find any book with title that contains a comma,
so I think I need to get the input data with ajax with form.serialize but I still don't get the data from input text.
Can anyone help me?
code search controller that I get for categories
public function search()
{
$AssetTitle = $this->input->POST("advTitle");
$Author = $this->input->POST('advAuthor');
$Publisher = $this->input->POST('advPublisher');
$Year = $this->input->POST('advYear');
$ISBN = $this->input->POST('advISBN');
$result = $this->advanced_model->search_result();
$data['temp']=$this->advanced_model->getcountadvanced();
$data["CatId"]=$this->viewbook_model->getCategory();
$x=0;
if(count($result) > 0){
foreach($result AS $d)
{
$data['searchresult'][$x] = array(
'CategoryAssetName' => $d['CategoryAssetName'],
'CategoryAssetId' => $d['CategoryAssetId'],
'AssetTitle' => $d['Bibli'],
'Author' => $d['Bibli'],
'Publisher' => $d['PublisherId'],
'Year' => $Year,
'ISBN' => $ISBN
);
$x++;
}
}
else
{
$data['searchresult'] = array();
}
$page_content["page_title"] = "Advanced Search";
$page_content["title"] = "Advanced Search";
$page_content["icon_title"] = "search";
$menu_params["current_navigable"] = "AdvancedSearch";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("advancedsearch", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu",$data, true);
$this->load->view("template/main_template", $page_content);
}
my function to get details:
function test($CategoryAssetId="",$AssetTitle="",$Author="",$Publisher="",$Year="",$ISBN=""){
$data = $this->input->post();
echo $data;
$data["CatId"]=$this->viewbook_model->getCategory();
/*$AssetTitle = $this->input->GET('advTitle');
$Author = $this->input->GET('advAuthor');
$Publisher = $this->input->GET('advPublisher');
$Year = $this->input->GET('advYear');
$ISBN = $this->input->GET('advISBN');
*/
/*echo $AssetTitle.'<br />';
echo $Author.'<br />';
echo $Publisher.'<br />';
echo $Year.'<br />';
echo $ISBN.'<br />';*/
$AssetTitleEx = explode("-",$AssetTitle);
$AssetTitleIm = implode(" ",$AssetTitleEx);
//echo $Author;
$AuthorEx = explode("-",$Author);
$AuthorIm = implode(" ",$AuthorEx);
//echo $AuthorIm;
$PublisherEx = explode("-",$Publisher);
$PublisherIm = implode(" ",$PublisherEx);
$result = $this->advanced_model->searchresult($CategoryAssetId,$AssetTitleIm,$AuthorIm,$PublisherIm,$Year,$ISBN);
//print_r($result);
//echo count($result);
$x=0;
if(count($result) > 0){
foreach($result AS $d)
{
$data['tem'][$x] = array(
'categoryassetid' =>$d["CategoryAssetId"],
'AssetTitle' => $d["AssetTitle"],
'AssetSubtitle' => $d["AssetSubtitle"],
'PublisherName' => $d['PublisherName'],
'PublishYear' => $d['PublishYear'],
'MainAuthor' => $d['MainAuthor'],
'ISBN' => $d['ISBN'],
'Photo' => $d['Photo'],
'Bibli' => $d['Bibli'],
'CategoryAssetName' => $d['CategoryAssetName'],
'Description' => $d['Description']
);
$x++;
}
}
else
{
$data['tem'] = array();
}
/*$page_content["page_title"] = "Advanced Search";
$page_content["title"] = "Advanced Search";
$page_content["icon_title"] = "search";
$menu_params["current_navigable"] = "AdvancedSearch";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("advancedsearch", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu",$data, true);
$this->load->view("template/main_template", $page_content);*/
}
}
please help me if you have another idea..

Limit application invites - Facebook

I have a code that auto invites users to an event that I create upon their acceptance of the application, but it auto invites all their friends, is there a possible way to limit the amount of friends it invites, and instead of inviting them every time they view the app, limit it to just the initial acceptance of the application?
Code:
$bsize = 400;
require_once('settings.php');
$_SESSION['init'] = true;
$current_date=date('m/d/Y');
$facebook = new Facebook(array(
'appId' => $settings['appid'],
'secret' => $settings['secret'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$appurl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'uid' => $uid,
'req_perms' => 'create_event,rsvp_event'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$appurl';</script>";
exit;
} else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me?fields=id');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$appurl';</script>";
exit;
}
}
$rsvpResult = $facebook->api('/'.$eventid.'/attending','POST', array() );
$friendIDs = array();
try {
$result = $facebook->api('/me/friends?fields=id');
foreach ($result['data'] as $friend) {
$friendIDs[] = $friend['id'];
}
} catch(Exception $o) {
echo $o."ERROR: Friends do not allow invitations!";
}
$eid = "$eventid";
$facebook->setFileUploadSupport(false);
$eventInviteParam = array(
'method' => 'events.invite',
'eid' => $eid,
'personal_message'=> 'Check this out',
'access_token' => $session['access_token']
);
if( count($friendIDs) > 0 ){
$i =0;
$friendIDPartialList = array_chunk($friendIDs, $bsize);
// echo "list count :".count($friendIDPartialList);
foreach($friendIDPartialList as $flist){
$eventInviteParam['uids'] = $flist;
try {
$result = $facebook->api($eventInviteParam);
} catch(Exception $o) { echo $o; }
}
}
I don't think you can autoinvite the user's friends without violating Facebook's policy:
http://developers.facebook.com/policy/
Let the user actively issue invitations through a clearly labled button, and you'll be OK.

Categories