Pull data from SqlServer Database into jQuery Full Calendar using codeigniter3 - json

I am facing same issue from so many days... Previously I worked with same calendar with PHP, but my project is in Codeigniter, so it is not fitted into my project... So now I am working with Codeigniter..
Controller Code
class Calendar extends CI_Controller
{
public function __construct()
{
Parent::__construct();
$this->load->model('Calendar_model');
}
public function index()
{
$this->load->view('Calendar_view');
}
public function load()
{
$query = $this->Calendar_model->load_events();
$data_events = array();
foreach($query->result() as $row)
{
$data_events[] = array(
"title" => $row->title,
"start" => date('Y-m-d H:i:s',strtotime($row->start_event)),
"end" => date('Y-m-d H:i:s',strtotime($row->end_event))
);
}
echo json_encode($data_events);
}
}
Model Code
class Calendar_model extends CI_Model
{
public function __construct()
{
Parent::__construct();
}
public function load_events()
{
$query = $this->db->get("events");
return $query;
}
}
When I run the above with this url http://localhost/calendar_sql_copy/index.php/Calendar/load,
I got following data
[{"title":"Meeting2","start":"2019-09-30 00:00:00","end":"2019-09-30 00:00:00"},{"title":"Meeting2","start":"2019-02-08 00:00:00","end":"2019-03-08 00:00:00"}]
But when I try to pull same data into Fullcalendar in following way..
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
selectable:true,
selectHelper:true,
// events:[
// {
// "title":"Meeting2",
// "start":"2019-09-30 00:00:00",
// "end":"2019-09-30 00:00:00"
// }
// ]
events:'<?php echo site_url('Calendar/load'); ?>'
</script>
If I show same data in static way as
events:[
{
"title":"Meeting2",
"start":"2019-09-30 00:00:00",
"end":"2019-09-30 00:00:00"
}
]
It pops up into calendar,
But when I try to render with URL like below,
events:'<?php echo site_url('Calendar/load'); ?>'
Here is the data from the browser Network tool: https://intouchsystems-my.sharepoint.com/:u:/g/personal/gurubaran_k_icsoft_co_in/EZE8m-w3Pn1HoktYxL2yHPQBKcuosFXP1M3uT69bh9qn9Q?e=4%3a5RjKNu&at=9
It does not show even my Calendar....
Where I done mistake please tell me....
It is very important module in my project...
In my organization no WebDevelopers are there, and I am new to this Codeigniter...

Based on the information provided both in the question and the comments, the the reason for the problem is this:
<!-- Calendar.php --> <!-- Calendar_model.php -->
in your AJAX Response. Your response must contain JSON only and nothing else. No other text, no whitespace at the start and end...nothing except the JSON. If you include other data like this then jQuery (and thus fullCalendar) cannot parse the JSON correctly.
Please ensure that the server is not outputting extra data in the response. That will fix the problem.

Related

Why does Laravel redirect to a wrong id after DB::listen?

I would like to store every query I run inside my application. To do that, I've created a "loggers" table, a Logger modal and this function inside my boot AppServiceProvider
DB::listen(function($query) {
$logger = new Logger;
$logger->query = str_replace('"', '', $query->sql);
$logger->bindings = json_encode($query->bindings);
$logger->created_at = Carbon::now();
$logger->save();
});
Well, anytime I run an insert query, Laravel returns the loggers table ID instead of the model last inserted ID.
Why on earth does this happen?
public function store(CycleRequest $request) {
$appointment = new Appointment;
$appointment-> ... same data ...
$appointment->save();
if ( ! $errors ) ){
$msg['redirect'] = route('appointments.edit', $appointment);
// The page redirects to last logger id
}
}
I think you want to do triggers so I recommend use events for this, o maybe you can take the structure of you table "loggers" and do two differents querys each time that you do querys.
After searching a lot, I found a solution creating a Middleware. Hope this may help someone else.
I've created a QueryLogMiddleware and registered in 'web' middleware, but you may put it everywhere you want:
public function handle($request, Closure $next)
{
\DB::enableQueryLog();
return $next($request);
}
public function terminate($request, $response)
{
$queries = \DB::getQueryLog();
foreach ($queries as $query)
{
// Save $query to the database
// $query["query"]
// $query["bindings"]
...
}
\DB::disableQueryLog();
\DB::flushQueryLog();
}

I can't get the data in appends with json in Laravel

I have two models in laravel project Item and ItemImgs
Item.php
class Item extends Model
{
protected $appends = [
'photo',
];
public function imgs()
{
return $this->hasMany(ItemImage::class);
}
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src;
}
}
it's worked in views
dd(Item::all()); //worked
{{ $cane->photo}}; //worked
but when I try to get json
return response()->json([
'items' => Item::with('imgs')->get(),
]);
// not worked. Got timeout 500
You cannot use dot notation in PHP.
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src; // Dot notation is not allowed
}
but you've to use:
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img->src;
}
if what you're trying to do is to get the items that have imgs() then what you should do is query by relationship existence, as mentioned in the docs
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence
'items' => Item::has('imgs')->get()
It is not possible to refer to the linked model tables in attributes. It works in views but gives out a memory error when outputting an array through json.
public function getPhotoAttribute(){
$img = ItemImage::where('item', $this->id)-
>first();
}
It works that way, but it's not elegant.

store session id in another table in codeigniter

i have one login page for vendor..after vendor logged in they redirect to vendor_dashboard..there i am getting vendor id with dashboard link..and i am getting that particular vendor name in my dashboard page..
In vendor dashboard..vendor has one tab called candidates..when they click on that tab they redirect to add_candidate page..so when vendor submit the form i want to store that vendor_id in candidates table..
In candidates_table there is one column called vendor_id..after submit i want to store that vendor_id for that particular candidate..
I am trying to do this..from past 6 hours..still it's not storing..
The problem is i didn't get anyidea on how to do this..
Login page:
if($this->input->post())
{
$user = $this->LoginModel->login($this->input->post());
if(count($user)>0)
{
$data = array(
'user_id' => $user['user_id'],
'first_name' => $user['first_name'],
'email' => $user['email'],
'password' => $user['password']
);
$this->session->set_userdata($data);
if($user['user_type_id'] == '1')
{
// redirect(base_url('index.php/Login/vendor_dashboard/'.$data['first_name']));
redirect(base_url('index.php/Login/vendor_dashboard/'.$this->session->user_id));
}
elseif($user['user_type_id'] == '2')
{
// (base_url('index.php/Login/user_dashboard/'.$this->session->user_id));
}
else
{
redirect(base_url('index.php/Login/dashboard'));
}
}
Dashboard:
<?= ($this->session->first_name)? $this->session->first_name : "" ?>
Can anyone help me..
Thanks in advance..
Your questions is some how related to this post. Anyway here is what you can do. Start with Authentication using User Controller or name it login or whatever you are comfortable with
class Users extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
$data['title']='Vendors Application';
if($_POST)
{
$user=$this->user_model->checkUser($_POST);
if(count($user)>0)
{
$this->session->set_userdata($user);
redirect(base_url().'dasboard/vendor');
}
}
else
{
$this->load>view('login',$data);
}
}
}
The function to check your user in database in User Model is as follows
public function checkUser($data)
{
$st=$this->db->select('*')->from('users')
->WHERE('email',$data['email'])
->WHERE('password',md5(sha1($data['password'])))
->get()->result_array();
if(count($st)>0)
{
return $st[0];
}
else
{
return false;
}
}
Once you are logged in and redirected to dashboard, add the candidate using Dashboard Controller or whatever you are comfortable to call it.
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function vendor()
{
$data['title']='Vendor Dashboard';
if($_POST)
{
//validation
$this->user_model->addCandidate($_POST);
$data['success']='Candidate Added Successfully';
$this->load->view('vendor_dashboard',$data);
}
else
{
$this->load->view('vendor_dashboard',$data);
}
}
}
The function in user model to add the candidate is as follows.
public function addCandidate($data)
{
$candidate=array(
'user_id'=>$this->session->userdata['id'],
'first_name'=>$data['first_name'],
'last_name'=>$data['last_name'],
'address'=>$data['address'],
'contact'=>$data['contact']
);
$this->db->insert('candidates',$candidate);
return $this->db->insert_id();
}
Remember you already have the vendor id in your session when you logged him in and stored his record in the session so there is no need to send the controller url any id to load the dashboard.
I hope you know about CI Form Validation if not please find it here

Yii2 POST image to model in API without Yii2 Naming convention

I'm creating an endpoint for a mobile application to send a image to the server. I'm posting the image with the POSTMAN extension for chrome. The image is in the $_FILES variable, and named image. How can I load this image into a model, or the UploadedFile class? The $model->load(Yii::$app->request->post()) line does not correctly load the file, as it is not in Yii2's naming convention for forms.
It's currently returning:
{
"success": false,
"message": "Required parameter 'image' is not set."
}
Code
models\Image.php
<?php
namespace api\modules\v1\models;
use yii\base\Model;
use yii\web\UploadedFile;
class Image extends Model
{
/**
* #var UploadedFile
*/
public $image;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
$path = dirname(dirname(__FILE__)) . '/temp/';
if ($this->validate()) {
$this->image->saveAs($path . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
die(var_dump($this->errors));
return false;
}
}
}
controllers\DefaultController.php
<?php
namespace api\modules\v1\controllers;
use api\modules\v1\models\Image;
use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;
class DefaultController extends Controller
{
public $enableCsrfValidation = false;
public function actionIndex()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new Image();
if (Yii::$app->request->isPost) {
if($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// file is uploaded successfully
return ['success' => true, 'message' => 'File saved.'];
}
else return ['success' => false, 'message' => 'Could not save file.'];
}
else return ['success' => false, 'message' => 'Required parameter \'image\' is not set.'];
}
else return ['success' => false, 'message' => 'Not a POST request.'];
}
}
Postman
Your problem seems to be the name you are using to send the image file. Usually Yii2 uses names for form attributes like "ModelName[attributeName]" and you are sending your image file with the name "image"
There are 2 ways of fixing this:
Change the name you use to send your image file to follow the same naming conveniton. However you don't seem to want that.
Use getInstanceByName('image') method instead of getInstance($model, 'image')
The problem come here
When you send files via api they are not sent asynchronously. If you check
echo '<pre>';
print_r($_FILES); //returns nothing
print_r($_POST["image"]); //returns something
echo '</pre>';
die;
One reason is that your controller extendsyii\web\controller which is not used by rest apis, extend yii\rest\controller
The other way to go about this is by using javascript formData when sending the post request
This is a way i handled a previous ajax post of an image probably itll give you a guideline
The form
<?php $form = ActiveForm::begin(['options' => ['enctype' =>
'multipart/form-data','id'=>'slider_form']]); ?> //dont forget enctype
<?= $form->field($model, 'file')->fileInput() ?>
Then on the ajax post
var formData = new FormData($('form#slider_form')[0].files);
$.post(
href, //serialize Yii2 form
{other atributes ,formData:formData}
)
Then on the controller simply access via
$model->file =$_FILES["TblSlider"]; //here this depends on your form attributes check with var_dump($_FILES)
$file_tmp = $_FILES["TblSlider"]["tmp_name"]["file"];
$file_ext = pathinfo($_FILES['TblSlider']['name']["file"], PATHINFO_EXTENSION);
if(!empty($model->file)){
$filename = strtotime(date("Y-m-d h:m:s")).".".$file_ext;
move_uploaded_file($file_tmp, "../uploads/siteimages/slider/".$filename);
///move_uploaded_file($file_tmp, Yii::getAlias("#uploads/siteimages/slider/").$filename);
$model->image = $filename;
}
I hope this helps

cakephp 3 + can't update database record when using translate behavior and 'contain'

I am using CakePHP 3 and trying to do some pretty basic stuff.
I have two tables, articles and tags.
Articles belongs to tags, and I made table tags translatable by attaching Translate behavior.
class ArticlesTable extends Table {
public function initialize(array $config) {
$this->addAssociations([
'belongsTo' => ['Tags']
]);
}
}
class TagsTable extends Table {
public function initialize(array $config) {
$this->addAssociations([
'hasMany' => ['Articles'],
]);
$this->addBehavior('Translate', ['fields' => ['name']]);
}
}
In Article controller I have edit function:
class ArticlesController extends AppController {
public function edit($id = null) {
$article = $this->Articles->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been updated.'));
return $this->redirect(['action' => 'edit',$id]);
}
$this->Flash->error(__('Unable to update your article.'));
}
$this->request->data = $article;
$tags = $this->Articles->Tags->find('list');
$this->set('tags', $tags);
}
}
In AppController I am setting locale language and at this point everything works fine, in edit.ctp file tags names are in local language and updating is working as it should.
BUT, when I replaced following line in edit function in ArticlesController:
$article = $this->Articles->get($id);
with line:
$article = $this->Articles->get($id, ['contain' => ['Tags']]);
I can no longer update article's tag.
If I change body and tag in my edit form, only new body is saved to my database. No error occurred, but tag_id is simply not changing.
If I remove translate behavior from the tags table, tags are not shown in local language, but can be updated again.
I am completely stuck, have no idea in which direction to search, why I can not use translate behavior and 'contain' at the same time?
Any help is greatly appreciated.