Ajax $.post method for load project tasks in fullcalendar - events

Good morning,
I'd like to add a fullcalendar to my mvc project.
The problem arrives when I try to encode the json with the project tasks. The code that I use is the following:
proyectosModel.php
public function obtenerTareasProyecto($idProyecto){
$sql = "SELECT tareasProyectos.nombre as title, tareasProyectos.fechaInicio as start, tareasProyectos.fechaLimite as end, tareasProyectos.estado , proyectos.idProyecto, proyectos.nombre as NombreProyecto, usuarios.codUsuario, usuarios.nombre, usuarios.apellido1, usuarios.apellido2\n";
$sql .= "FROM tareasProyectos\n";
$sql .= "JOIN proyectos on tareasProyectos.FKidProyecto = proyectos.idProyecto\n";
$sql .= "JOIN usuarios on tareasProyectos.FKusuarioAsignado = usuarios.codUsuario\n";
$sql .= "WHERE tareasProyectos.FKidProyecto ='" . $idProyecto . "'";
$tareasProyecto = $this->_db->query($sql);
return $tareasProyecto->fetchall(PDO::FETCH_ASSOC);
}
proyectosController.php
public function obtenerTareasProyecto() {
echo json_encode($this->_proyectos->obtenerTareasProyecto($this->getTexto('idProyecto')));
}
proyectos.js
$(document).ready(function(proyecto){
var cargarTareas = $.post('/distribucion/proyectos/obtenerTareasProyecto',
{
idProyecto: proyecto
}, function(datos){
//Here I need to link the title, start and end properties.
}, 'json'}
//Cargamos el calendario principal
$("#calendario").fullCalendar({
weekMode:'variable',
header:{ //Cabecera
left: 'month,basicWeek,agendaDay',
center: 'title',
right: 'today prev,next'
},
firstDay:1, //Primer día de la semana
selectable: true, //Fechas seleccionables
titleFormat:{//Formato del título del calendario
month: "MMMM yyyy",
week: "d 'd&#101' MMMM",
day: "dddd, d 'd&#101' MMMM, yyyy"
},
columnFormat:{
month:"dddd",
week:"dddd d/M",
day:"dddd d/M"
},
monthNames:['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
monthNamesShort:['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
dayNamesShort:['Dom','Lun','Mar','Mie','Jue','Vie','Sab'],
buttonText:{
month:'mes',
week:'semana',
day: 'día',
today:'Hoy'
},
eventSources: [
{
events: //¿how can I do with the $.post() method?
}
]
});
}
In the javascript file I load the ajax with $.post() method but I don't know how can I request the title, start and end properties of each event or project task.
Cheers.
Francisco J.

I think what you need to do is assign your php call as an eventSource something like they have in the Events (as a json feed) jquery.ajax example. You'll want to specify parameters as something like...
events: {
url: '/distribucion/proyectos/obtenerTareasProyecto',
type: 'POST',
data: {
idProyecto: proyecto
}
}
It will then take the JSON return and (if it's properly formatted) convert it into calendar events.
Hope this helps!

Related

Filtering the data on the basis of daterangepicker in laravel

I want to apply date range filter to my specific page .. There is just one date range picker which allows you to select a range from the calender and it shows in a single variable. i am getting the data in that variable but i dont know the exact way to filter my database data by splitting single variable value in two values ( from and to ) .
This is my input box --
<input type="text" class="form-control" name="daterange" value="01/01/2021 - 01/15/2021" />
Below is my specific script for daterange -
$(function() {
$('input[name="daterange"]').daterangepicker({
"startDate": "11/01/2021",
"endDate": "11/07/2021",
opens: 'left'
}, function(start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
axios.get('/fetchdata')
.then(response => {
data = this.form;
})
});
});
This is my web.php
Route::get('fetchdata', 'AccessoryController#fetch_data')->name('accessory.date.filter');
and this is my controller code where i need help , for now daterange picker is working. Its giving me correct selection in console. "New date range selected: 2021-11-04 to 2021-11-10 (predefined range: undefined)"
and my route is also working with return 'test' but i dont know how to get data at the back end.
public function fetch_data(Request $request)
{
//return 'test';
return $request->all(); // This returns nothing
$user = Auth::user();
$storesID = $user->storesID->pluck('id');
$stores = $user->stores;
return $request->daterange;
$accessory = AccessoryRequest::where('request_date', ">=", $request->startDate)->where('date', "<=", $request->endDate)->get(); //how can i filter
return $accessory;
return view('accessorydetails.index')
->with('stores', $stores)
->with('accessories', $accessories);
}
You do not put any parameters to the server:
axios.get('/fetchdata', {
params: {
startDate: start.format('YYYY-MM-DD'),
endDate: end.format('YYYY-MM-DD')
}
}).then(response => {
data = this.form;
});
Regarding AccessoryRequest, I guess you mean Accessory Eloquent object to work with the database
$accessory = AccessoryRequest::where('request_date', ">=", $request->startDate)->where('date', "<=", $request->endDate)->get(); //how can i filter
I am not sure how the name of the date field is, but idea is to do smth like
$accessory = AccessoryRequest::where('created_at', ">=", $request->get('startDate'))
->where('created_at', "<=", $request->get('endDate'))
->get();
In web.php --
Route::post('fetchdata', 'AccessoryController#fetch_data')->name('accessory.date.filter');
and in script file
$(function () {
$('input[name="daterange"]').daterangepicker({
"startDate": "11/01/2021",
"endDate": "11/07/2021"
}, function(start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
axios.post('/fetchdata/', {
startDate: start.format('YYYY-MM-DD'),
endDate: end.format('YYYY-MM-DD'),
}).then(response => {
$(location).attr('href', '/accessory')
//console.log(startDate);
});
});
});
Axios was not working with get method.

Kendo UI grid column template with nested evaluations - how to?

Kendo UI v2015.2.805
I have a KendoGrid with a template column that does a conditional to determine if a set of buttons should be added, if so additional evaluations are needed, and I can't figure out how to nest them.
The below works but does not have the required additional evaluation:
{ field: "Served", title: "Served",
template: "<div>" +
"#= (Kind==0 || Kind==7) ? '" +
"<button type=\"button\" data-id=\"12345\">Yes</button>" +
"<button type=\"button\" data-id=\"54321\">No</button>" +
"' : " +
"'NO BUTTON HERE'" +
"#</div>"
I multi-lined it to try to get it to look good, which it does not. The idea is that if the Kind = 0 or 7 then show two buttons otherwise do not. Works great.
However I need to evaluate the data-id to #= ID #, so I try:
" <button type=\"button\" data-id=\"' #= ID # '\">Yes</button>"
I know I need to 'drop out' of the quoted string to get the evaluation to work and since I have used double quotes for the whole expression I am returning the button in the conditional as a single quoted string, and as such escaping the button attributes, but I can't get it to evaluate the #=.
I've tried so many different combinations I've lost track.
So what is the 'right-way' to do this?
A SOLUTION:
Accepting David's answer with a modification to use template evaluation in the function:
{ field: "Served", title: "Served",
template: function (data) {
switch (data.Kind) {
case 0:
case 7:
var template = kendo.template("<button type='button' data-id='#= ID #' >Yes</button><button type='button' data-id='#= ID #'>No</button>");
return template(data);
default:
return '';
}
}
Having the function perform the initial test removes one level and allows 'normal' evaluation to occur.
You can use a function instead I Beleive it will would make things so much easier for you.
your template can be "#= buildButtons(data) #"
function buildButtons(model) {
if (model.Kind == 0 || model.Kind == 7) {
return "hello world";
}
return "";
}
here is a code sample
https://dojo.telerik.com/UQuqAfuv
<div id="grid"></div>
<script>
var people = [
{ id: 1, firstName: 'David', lastName: 'Lebee' },
{ id: 2, firstName: 'John', lastName: 'Doe' }
];
$('#grid').kendoGrid({
dataSource: {
transport: {
read: function(options) {
options.success(people);
}
}
},
columns: [
{ field: 'firstName', title: 'First Name' },
{ field: 'lastName', title: 'Last Name' },
{ title: 'Actions', template: '#= buildActions(data) #'}
]
});
function buildActions(model) {
if (model.firstName == "David") {
return 'Hello David';
}
return '';
}
</script>

Make a typeahead remote call to codeigniter controller

I want to be able to make a remote data call from bloodhound using typeahead to model with codeigniter.
So I was struggling a bit trying to get typeahead (twitter) remote data and codeigniter to work together, I dint't find a good example that fit with my needs. After a few hours I came up with the following code, hope it helps.
The View:
var proyectos = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.proyecto_titulo); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'proyectos/proyectos/getProyectos?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#titulo').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'proyectos',
displayKey: 'proyecto_titulo',
source: proyectos.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No se encontraron registros que coincidan con la búsqueda.',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p>{{proyecto_titulo}} – <strong>{{tipo_proyecto_nombre}}</strong> </p>')
}
});
The relevant part here is:
remote: {
url: 'proyectos/proyectos/getProyectos?query=%QUERY',
wildcard: '%QUERY'
}
Where proyectos/proyectos is the controller path and getProyectos is the method that answers the request.
Whenever you type, and based on the minLength setting, is going to request a matching string in the back-end.
Note: In order to use the suggestion part in the templates setting, you must download the handlebars.js library.
The Controller:
public function getProyectos() {
$consulta = $this->input->get('query');
$proyectos = $this->proyectos_model->getProyectos($consulta);
if($proyectos->num_rows() > 0){
echo json_encode($proyectos->result());
}
else{
echo '';
}
}
We first get the query string from the view with $this->input->get('query') and afterwards pass it to our model.
The Model:
public function getProyectos($consulta) {
$query = $this->db->query
("select pro.proyecto_id
,pro.proyecto_titulo
,tip.tipo_proyecto_nombre
,tip.tipo_proyecto_id
from proyectos pro
inner join tipos_proyectos tip on tip.tipo_proyecto_id = pro.tipo_proyecto_id
where pro.proyecto_titulo ilike '%" . $consulta . "%' ");
return $query;
}
Here in the model we simply pass the query string to our sql select statement and we're done. The database I'm using is postgresql.
I hope you find this helpful.

Bootstrap Typeahead with AJAX source (not working)

I'm trying to implement a search bar dropdown using bootstrap v3.0.0 with typeahead.js.
My search bar will take a student's firstname and lastname. I'm using a MYSQL database which consists of a table called practice with afirstname, alastname, aid as columns. The search bar should not only contain the firstname and lastname in the dropdown, but also the id associated with it in a second row. I've read all the examples on the typeahead.js page and I'm unable to do it with ajax call.
Below is the code of my index.php
JS
<script type="text/javascript">
$(document).ready(function() {
$('.cr.typeahead').typeahead({
source: header: '<h3>Select</h3>',
name: 'accounts',
source: function (query, process) {
return $.getJSON(
'localhost/resultly/source.php',
{ query: query },
function (data) {
return process(data);
});
});
});
</script>
HTML:
<body>
<div class="container">
<br/><br/>
<input type="text" name="query" class="form-control cr typeahead" id="firstname" />
<br/><br/>
</div>
</body>
Code for source.php : This should return the firstname and lastname from my database in the form of a json string or object?
<?php
$query = $_POST['query'];
try {
$conn = new PDO('mysql:host=localhost;dbname=practice','root','');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
$stmt->execute();
}
catch (PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
foreach ($stmt as $row) {
$afirstname[] = $row['afirstname'];
$alastname[] = $row['alastname'];
}
echo json_encode($afirstname);
echo json_encode($alastname);
?>
result:
http://oi41.tinypic.com/50moi1.jpg
Nothing shows up. I've tried adding a prefetch:
prefetch: {
url: 'localhost/resultly/source.php',
filter: function(data) {
r1 = [];
for (var i = 0; i < data.length; i++) {
r1.push({
value: data[i].afirstname,
tokens: [data[i].afirstname, data[i]alastname],
afirstname: data[i].afirstname,
alastname: data[i].alastname,
template: '<p>{{afirstname}} - {{alastname}}</p>',
});
}
return r1;
}
}
Please do provide a solution or an example which I could refer.
Update:
The source.php should return a list of json encoded data. I debugged by looking at the output that the source.pho created. What I did wrong was whenever I was supposed to put a url I did localhost/source.php instead of just source.php.
Solution provided by Bass Jobsen works and now I have run into another problem.
I'm using
if(isset($_POST['query']))
{ $q_uery = $_POST['query'];
$query = ucfirst(strtolower($q_uery))};
to take the user's data and use it for searching logic
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
The updated source.php is http://pastebin.com/T9Q4m10g
I get an error on this line saying Notice: Undefined variable: stmt I guess the $query is not being initialized. How do I get this to work. Thanks.
Update 3
I used prefetch: instead of 'remote:' that did all the matching.
Your return is not correct:
echo json_encode($afirstname);
echo json_encode($alastname);
See for example Twitter TypeAhead.js not updating input
Try echo json_encode((object)$stmt);, see: typeahead.js search from beginng
Update
I tried echo json_encode((object)$stmt);still doesn't work.
Do you use any kind of debugging? What does? source.php return? Try to follow the steps from
typeahead.js search from beginng without the filter.
html:
<div class="demo">
<input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
</div>
javascript:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10
});
php (source.php):
<?php
$people = array();
$people[] = array("lastname"=>"Inaw",
"firstname"=>"Dsajhjkdsa");
$people[] = array("lastname"=>"Dsahjk",
"firstname"=>"YYYsgbm");
$people[] = array("lastname"=>"Dasjhdsjka",
"firstname"=>"JHJKGJ");
$datums = array();
foreach($people as $human)
{
$datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
}
echo json_encode((object)$datums);
This should work
update2
Thanks, it worked. How do I display 2 or more 'value'?
add some values to your datums in source.php:
foreach($people as $human)
{
$datums[]=(object)array
(
'value'=>$human['firstname'],
'tokens'=>array($human['firstname'],$human['lastname']),
'firstname'=>$human['firstname'],
'lastname'=>$human['lastname']
);
}
firstname and lastname now are field you csn use in your templates
Add a template and template engine to your javascript declaration:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10,
template: [
'<p>{{firstname}} - {{lastname}}</p>'
].join(''),
engine: Hogan
});
The above make use of https://github.com/twitter/hogan.js. You will have to include the template engine by javascript, for example:
<script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"></script>
It is working for me. please follow below step.
Please add below Js and give proper reference.
bootstrap3-typeahead
--- Ajax Call ----
$("#cityId").keyup(function () {
var al = $(this).val();
$('#cityId').typeahead({
source: function (valuequery, process) {
var states = [];
return $.ajax({
url: http://localhost:4000/GetcityList,
type: 'POST',
data: { valueType: "", valueFilter: valuequery },
dataType: 'JSON',
success: function (result) {
var resultList = result.map(function (item) {
states.push({
"name": item.Value,
"value": item.Key
});
});
return process(states);
}
});
},
});
});
---- Cs Code ---
public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
{
List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
return Json(returnValue);
}
Auto suggest of Bootstrap typehead will get accept only "name" and "value" so create reponse accordinly

In Backbone Collection, delete a model by link on itself

Im just trying to delete a model from a collection, with a link on itself.
I've attach the event to the "Eliminar button" but it seems Im losing the reference to the model element that contains it... and can't find it.. can you?:
(function ($) {
//Model
Pelicula = Backbone.Model.extend({
name: "nulo",
link: "#",
description:"nulo"
});
//Colection
Peliculas = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind("add", options.view.addPeliculaLi);
this.bind("remove", options.view.delPeliculaLi);
}
});
//View
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.peliculas = new Peliculas( null, { view: this });
//here I add a couple of models
this.peliculas.add([
{name: "Flying Dutchman", link:"#", description:"xxxxxxxxxxxx"},
{name: "Black Pearl", link: "#", description:"yyyyyyyyyyyyyy"}
])
},
events: {"click #add-movie":"addPelicula", "click .eliminar":"delPelicula"},
addPelicula: function () {
var pelicula_name = $("#movieName").val();
var pelicula_desc = $("#movieDesc").val();
var pelicula_model = new Pelicula({ name: pelicula_name },{ description: pelicula_desc });
this.peliculas.add( pelicula_model );
},
addPeliculaLi: function (model) {
var str= model.get('name').replace(/\s+/g, '');
elId = str.toLowerCase();
$("#movies-list").append("<li id="+ elId +"> " + model.get('name') + " <a class='eliminar' href='#'>Eliminar</a> </li>");
},
delPelicula: function (model) {
this.peliculas.remove();
console.log("now should be triggered the -delPeliculaLi- event bind in the collection")
},
delPeliculaLi: function (model) {
console.log(model.get('name'));
$("#movies-list").remove(elId);
}
});
var appview = new AppView;
})(jQuery);
And my html is:
<div id="addMovie">
<input id="movieName" type="text" value="Movie Name">
<input id="movieDesc" type="text" value="Movie Description">
<button id="add-movie">Add Movie</button>
</div>
<div id="lasMovies">
<ul id="movies-list"></ul>
</div>
There are several things in this code that won't work. Your major problem here is that you don't tell your collection which model to remove. So in your html you have to assign so unique id that later will identify your model.
// set cid as el id its unique in your collection and automatically generated by collection
addPeliculaLi: function (model) {
$("#movies-list").append("<li id="+ model.cid +"> <a href="+ model.get('link')+">" +
model.get('name') + "</a> <a class='eliminar' href='#'>Eliminar</a> </li>"
);
},
// fetch and delete the model by cid, the callback contains the jQuery delete event
delPelicula: function (event) {
var modelId = this.$(event.currentTarget).attr('id');
var model = this.peliculas.getByCid(modelId);
this.peliculas.remove(model);
// now the remove event should fire
},
// remove the li el fetched by id
delPeliculaLi: function (model) {
this.$('#' + model.cid).remove();
}
If there aren't other errors that I have overlooked your code should work now. This is just a quick fix. Maybe you should have a look at the todos example of Backbone to get some patterns how to structure your app.
http://documentcloud.github.com/backbone/examples/todos/index.html

Resources