Editing Fullcalendar javascript - javascript

I'm editing fullcalendar to adapt it to my needs.
First of all here is the code:
<!----HTML---->
<link href='assets/css/fullcalendar.css' rel='stylesheet' />
<link href='assets/css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='assets/js/moment.min.js'></script>
<script src='assets/js/jquery-ui.min.js'></script>
<script src='assets/js/fullcalendar_not_min.js'></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Scegli Zona di Servizio</h4>
</div>
<div class="modal-body" id="myModalBody">
<div class="form-group">
<label for="sel1">Select list (select one):</label>
<select class="form-control" id="mySelect">
<?php
foreach($zone_servizio_array as $zona){
echo '<option value="'.$zona->getId().'">'.$zona->getNome().'</option>';
}
?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="save();" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
<body>
<div id='wrap'>
<div id='external-events'>
<h4>Agenti</h4>
<?php
foreach ($agenti_array as $agente){
echo '<div class=\'fc-event\'>'.$agente->getNome().' '.$agente->getCognome().'</div>';
}
?>
<p>
<img src="assets/img/trashcan.png" id="trash" alt="">
</p>
</div>
<div id='calendar_buttons' align="left">
<div class="btn-group" role="group" aria-label="..." >
<button type="button" class="btn btn-success"><span class="glyphicon glyphicon-floppy-save" aria-hidden="true"></span> Salva</button>
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Ripristina</button>
</div>
</div>
<div id='calendar'></div>
<div style='clear:both'></div>
<xspan class="tt">x</xspan>
</div>
</body>
Here is the Javascript:
<script>
var salva = 0; //control variable
function save(){//to change the control variable value
salva = 1;
}
function saveEvent(event, title, start, zone){
$('#myModal').modal('show');
$('#myModal').on('hidden.bs.modal', function (e) {
zona_servizio = document.getElementById('mySelect').value;
if(salva == 1){
console.log('before save event', event, title, start, zone);
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&zona_servizio='+zona_servizio,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
}else{
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
});
//$('#calendar').fullCalendar('updateEvent',event);
salva = 0;
console.log('end save event', event);
}
$(document).ready(function() {
zone = "01:00"; //Change this to your timezone
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .fc-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
**eventReceive**: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
console.log('event Receive', event, title, start, zone);
saveEvent(event, title, start, zone);
},
eventDrop: function(event, delta, revertFunc) {
var title = event.title;
var start = event.start.format();
var end = (event.end == null) ? start : event.end.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventClick: function(event, jsEvent, view) {
console.log(event.id);
var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });
if (title){
event.title = title;
console.log('type=changetitle&title='+title+'&eventid='+event.id);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status == 'success')
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
},
eventResize: function(event, delta, revertFunc) {
console.log(event);
var title = event.title;
var end = event.end.format();
var start = event.start.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var con = confirm('Are you sure to delete this event permanently?');
if(con == true) {
$.ajax({
url: 'process.php',
data: 'type=remove&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
if(response.status == 'success'){
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
});
function getFreshEvents(){
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
process.php
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once __ROOT__.'/main/metodi.php';
include('config.php');
sec_session_start();
$type = $_POST['type'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$zona_servizio = $_POST['zona_servizio'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`, `zona_servizio`) VALUES('$title','$startdate','$startdate','false','$zona_servizio')");
$lastid = mysqli_insert_id($con);
$_SESSION['array_last_events'][] = $lastid;
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT calendar.id, calendar.title, calendar.startdate, calendar.enddate, zona_servizio.nome as zona_servizio, calendar.allDay FROM calendar LEFT JOIN zona_servizio on calendar.zona_servizio = zona_servizio.id");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$e['zona_servizio'] = $fetch['zona_servizio'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
array_push($events, $e);
}
echo json_encode($events);
}
if($type == 'zone_servizio')
{
$zone = array();
$query = mysqli_query($con, "SELECT * FROM zona_servizio");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['nome'] = $fetch['nome'];
$e['id_comune'] = $fetch['id_comune'];
array_push($zone, $e);
}
echo json_encode($zone);
}
?>
Explanation of the code and issue:
I'm using fullcalendar to drag and drop some events on the calendar. In the javascript this corresponds to Event receive.
After the event drop, the function saveEvent is called.
A modal is showed, with a select form.
Clicking on Save changes button, I get the selected option value and than I store the events information and this value in the DB using Ajax.
It's very linear.
When I drop the first event, everything works fine. The problem is when I drop more than one event without manually refresh the page.
Here what happen: I store the second event, but I re-store the first event too.
If I drop a third event, I re-store the first two events and the third.
I need help to understand the reason.
In the javascript I insert some console.log.
Here's the console output:
console_output
You can see at the end that the console.log "before save event" is repeated two times, with the first and second events data.
This means that at the second Event drop, the saveEvent function is called twice. So why does this happen?
I hope my question was clear. Thanks to everyone!

I resolved the issue. It was linked to the bootstrap modal.
I found this other post that helped me: link

Related

why required not working while uploading image with cropper js in php

Hello guys i am building a project where i have used cropper js to crop the uploaded image everything is working fine with my codes like file is getting cropped getting uploaded to database as well but the problem is while i want to check that the file field should not be empty i am using the required but its not working i am pasting the codes that i have used till now can you guys please see what do i need to do to rectify the errors please.
HTML
<form id="partyins" class="needs-validation" action="" method="post" enctype="multipart/form-data" novalidate>
<div class="col-md-12" style="padding:5%;">
<input type="file" id="image" class="form-control" required>
<input type="hidden" name="product_id" id="product_id" value="<?php if(isset($_GET['product_id'])){ echo $_GET['product_id']; } ?>">
<button type="submit" class="btn btn-success btn-block btn-upload-image mt-4" style="margin-top:2%">Upload Image</button>
</div>
</form>
JS PART
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 64,
height: 64,
type: 'circle' //square
},
boundary: {
width: 300,
height: 300
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$("#partyins").submit(function(e){
e.preventDefault();
var prod_id = $('#product_id').val();
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
if(img == ''){
toastr.error("Please upload a file",'Error');
}
$.ajax({
url: "model/product_image/product_image.php?insertimg&imgid="+prod_id,
type: "POST",
data: {"image":img},
success: function (data) {
var res = data;
if(res==8){
toastr.error("Sorry! There is an error",'Error');
}else if(res==9){
toastr.error("Please upload a file",'Error');
}else{
toastr.success(data,'Update');
$('#partyins')[0].reset();
}
}
});
});
});
PHP
if(isset($_GET['insertimg']) && isset($_GET['imgid'])){
$id = $_GET['imgid'];
$image = $_POST['image'];
list($type, $image) = explode(';',$image);
list(, $image) = explode(',',$image);
$image = base64_decode($image);
$image_name = 'product_id'.$id.'_'.time().'.png';
file_put_contents("../../../upload_products/".$image_name, $image);
if(!$image == ''){
$sql_inst = "UPDATE $tb_products SET `p_upload`='$image_name' WHERE id='$id'";
$res_inst = mysqli_query($conn,$sql_inst);
if($res_inst){
echo "Updated Successfully";
}else{
echo 8;
}
}else{
echo 9;
}
}
You can do it in this way I hope it may work
var image = $('#image').val();
if(image == ''){
toastr.error("Please upload a file",'Error');
}else{
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
$.ajax({
url: "model/product_image/product_image.php?insertimg&imgid="+prod_id,
type: "POST",
data: {"image":img},
success: function (data) {
var res = data;
if(res==8){
toastr.error("Sorry! There is an error",'Error');
}else if(res==9){
toastr.error("Please upload a file",'Error');
}else{
toastr.success(data,'Update');
$('#partyins')[0].reset();
}
}
});
});
}

Ajax onClick Safari iOS

I have a custom WordPress plugin that uses a Javascript ajax onClick function to make a clickable element that rondomly selects an item from a dropdown list and then opens that selection in a new tab.
The code works like a dream on every desktop and mobile browser except Safari on iOS.
In Safari on iOS if you click the random button it succeeds in randomly selecting an option from the select list and shows the loading animation but it fails to load the new page from the selection.
It seems that this bug is similar to other safari only ajax onClick bugs that have been discussed at length since the early days of iOS. Except that I have yet to find a workaround to this particular implementation.
I'm including code for both the random button where the bug is found and the select list as, based on my research to date, it may be the interaction of these two elements that is causing the bug on Safari.
Any thoughts?
(The following code has been sanitized to protect my client)
PHP in WordPress plugin
<div ><a href="javascript:;" id="randoms" class="tooltip">
<span class="tooltiptext" style="background : grey; opacity : 0.5;">Random</span>
</a></div>
<div class="select_able">
<div class="ruler"></div>
<img src="<?php echo CLIENT_WEBSITE_URL; ?>public/image/widget-background.jpg" alt="Widget">
<select name="person_profile" id="person_id">
<option value="0" >Search</option>
<?php if(!empty($search_person)): ?>
<?php foreach($search_person as $search_person): ?>
<option value="<?php echo $search_person->entity_id; ?>"> <?php echo $search_person->person_name ?> </option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
HTML Output
<div><a href="javascript:;" id="randoms" class="tooltip">
<span class="tooltiptext" style="background : grey; opacity : 0.5;">Random</span>
</a></div>
<div class="select_able">
<div class="ruler"></div>
<img src="https://image.url" alt="Widget" data-pagespeed-url-hash="123456" onload="pagespeed.CriticalImages.checkImageForCriticality(this);">
<select name="person_profile" id="person_id">
<option value="0">Search</option>
<!-- List with hundreds of options -->
</select>
</div>
Javascript in WordPress plugin
$("#randoms").on("click", function() {
$.ajax({
type: "post",
dataType: "json",
url: ajaxUrl,
data: {
action: "random_client"
},
beforeSend: function() {
$(".loader").removeClass("hide");
},
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
success: function(resp) {
$(".loader").addClass("hide");
if (resp.code == 200) {
var data = {
id: resp.entity_id,
text: resp.person_name
};
var newOption = new Option(data.text, data.id, true, true);
$("#person_id")
.append(newOption)
.trigger("change");
var pers_rating = $.trim($(".person_rating").val());
if (pers_rating < 0) {
$(".ruler").addClass("hide");
}
}
}
});
});
$(".new-tab-random").on("click", function() {
$.ajax({
type: "post",
dataType: "json",
url: ajaxUrl,
data: {
action: "random_client"
},
beforeSend: function() {
$(".loader").removeClass("hide");
},
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
success: function(resp) {
$(".loader").addClass("hide");
if (resp.code == 200) {
fetch_profile_tab(resp.entity_id, resp.person_name);
}
}
});
});
$(".loader").removeClass("hide");
$(document).on("click", ".lower", function() {
$("#designator").val("lower");
var designator = $("#designator").val();
feed_back(designator);
});
$(document).on("click", ".higher", function() {
$("#designator").val("higher");
var designator = $("#designator").val();
feed_back(designator);
});
function fetch_profile_tab(
person_new_tab_id = 0,
slug_name_new_tab = 0
) {
var person_id;
var slug_name;
if (person_new_tab_id != 0) {
person_id = person_new_tab_id;
slug_name = string_to_slug(slug_name_new_tab);
} else {
person_id = $("#person_id").val();
var data = $("#person_id").select2("data");
slug_name = string_to_slug(data[0].text);
}
if (window.location.hostname == "localhost") {
var new_link =
window.location.origin +
"/website/result/" +
person_id;
} else {
var new_link =
window.location.origin + "/result/" + person_id;
}
window.open(new_link, "_blank");
}
What if you try to replace href="javascript:;" with href="#" in your <a> tag?

Return Data with EventClick Full Calendar

Good afternoon guys, I need a help, I'm using Fullcalendar to create a simple calendar, I can already create events save them in the DB and display them in the calendar, now what I need is that when clicking on the event a popup ( Modal) is opened displaying the data of the event and also the option to perform an update of this data, I am already with the modal working when clicking on the event it is opened what I do not know is how to display the data saved in the BD in their respective fields Here are my codes:
Controler(calendar2.php):
class Calendar2 extends CI_controller{
function __construct(){
parent:: __construct();
$this->load->model('calendar2Model', 'model', TRUE);
}
public function index(){
$this->template->set('title', 'Agenda');
$this->template->load('layout', 'calendar_v.php');
//$this->load->view('calendar_v.php');
}
public function getEvents(){
$data = $this->model->get_events();
echo json_encode($data);
}
public function updateEvents(){
$param['id'] = $this->input->post('id');
$param['inicio'] = $this->input->post('inicio');
$param['fim'] = $this->input->post('fim');
$r = $this->model->updateEvents($param);
echo json_encode($r);
}
public function deleteEvents(){
$id = $this->input->post('id');
$r = $this->model->deleteEvents($id);
echo json_encode($r);
}
public function new_event(){
$this->template->set('title', 'Nova tarefa');
$this->load->library('form_validation');
/* Define as tags onde a mensagem de erro será exibida na página */
$this->form_validation->set_error_delimiters('<span>', '</span>');
/* Define as regras para validação */
$this->form_validation->set_rules('nomeEvento', 'Nome', 'required|max_length[40]');
$this->form_validation->set_rules('inicio', 'Data de inicio', 'trim|required|max_length[60]');
$this->form_validation->set_rules('importancia', 'Prioridade', 'trim|required|max_length[60]');
$this->form_validation->set_rules('descricaoEvento', 'descricaoEvento', 'trim|required|max_length[150]');
/* Executa a validação e caso houver erro chama a função index do controlador */
if ($this->form_validation->run() === FALSE) {
$this->template->load('layout', 'clientes_inserir.phtml');
/* Senão, caso sucesso: */
} else {
/* Recebe os dados do formulário (visão) */
$data['nomeEvento'] = $this->input->post('nomeEvento');
$data['inicio'] = $this->input->post('inicio');
$data['fim'] = date('Y-m-d', strtotime($this->input->post('inicio'). ' + 1 day'));
$data['user'] = $this->input->post('user');
$data['importancia'] = $this->input->post('importancia');
$data['importancia'] = $this->input->post('descricaoEvento');
/* Chama a função inserir do modelo */
if ($this->model->inserir($data)) {
$this->session->set_flashdata('mensagem', 'registro salvo com sucesso');
redirect('clientes');
} else {
$this->session->set_flashdata('mensagem', 'registro nao salvo');
}
}
}
}
Modal(calendar2model.php):
<?php
class calendar2Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function get_events(){
$this->db->select('idevento id,cnome title, inicio start, fim end');
$this->db->from('eventos');
$this->db->join('clientes','clientes.ccod = eventos.nomeEvento');
return $this->db->get()->result();
}
function inserir($data) {
return $this->db->insert('eventos', $data);
}
function updateEvents($param) {
$campos = array(
'inicio' => $param['inicio'],
'fim' => $param['fim']
);
$this->db->where('idevento', $param['id']);
$this->db->update('eventos', $campos);
if($this->db->affected_rows() == 1){
return 1;
} else{
return 0;
}
}
function deleteEvents($id){
$this->db->where('idevento', $id);
$this->db->delete('eventos');
if($this->db->affected_rows() == 1){
return 1;
} else{
return 0;
}
}
}
View(calendar_v.php):
<head>
<div class="row" >
<div class="col-sm-2">
<a data-toggle="modal" data-target="#new_event" class="btn btn-primary">Nova Tarefa</a>
</div>
</div>
<script>
$(document).ready(function() {
$.post('<?php echo base_url();?>calendar2/getEvents',
function(data){
//alert(data);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
editable: true,
events: $.parseJSON(data),
eventDrop: function(event, delta, revertFunc){
var id = event.id;
var fi = event.start.format();
var ff = event.end.format();
$.post("<?php echo base_url();?>calendar2/updateEvents",
{
id:id,
inicio:fi,
fim:ff,
},
function(data){
if(data == 1){
alert('Evento atualizado');
}else{
alert('Evento Nao atualizado')
}
});
},
eventResize: function(event, delta, revertFunc) {
var id = event.id;
var fi = event.start.format();
var ff = event.end.format();
$.post("<?php echo base_url();?>calendar2/updateEvents",
{
id:id,
inicio:fi,
fim:ff,
},
function(data){
if(data == 1){
//alert('Evento atualizado');
}else{
// alert('Evento não atualizado')
}
});
},
// eventClick: function(event,jsEvent, view){
// $('#calendar').fullCalendar('removeEvents',event.id);
// }
eventRender: function(event, element){
var el = element.html();
element.html("<div style='width:90%;float:left;'>" + el + "</div><div class='closeee' style='color:red; text-align:right;'>X</div>");
element.find('.closeee').click(function(){
if(!confirm("Excluir registro ??")){
revertFunc();
}else{
var id = event.id
$.post("<?php echo base_url();?>calendar2/deleteEvents",
{
id:id,
},
function(data){
if(data == 1){
$('#calendar').fullCalendar('deleteEvents', event.id);
//alert('Tarefa Excluida');
}else{
//alert('Tarefa não Excluida')
}
});
}
});
},
eventClick: function(event, jsEvent, view){
$('#mtitulo').html(event.title);
$('#autor').val(event.id);
$('#modalEvento').modal();
},
});
});
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
<!-- Modal visualizar-->
<div class="modal fade" id="modalEvento" tabindex="-1" role="dialog" aria-labelledby="mymodelLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-red">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="mymodelLabel"> Editar Evento</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group col-md-6">
<label for="nomeEvento">Nome Cliente</label>
<div class="form-control" id="mtitulo"></div>
</div>
<div class="form-group col-md-6">
<label for="user">Responsavel</label>
<div class="form-control" id="autor"></div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<div class="input-group date">
<input type="text" class="form-control date" id="inicio" name="inicio"/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label for="importancia">Prioridade</label>
<input type="text" class="form-control" id="importancia" name="importancia"/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="descricaoEvento">Descrição</label>
<input type="text" class="form-control" id="descricaoEvento" name="descricaoEvento"/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="closeM" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-danger" id="btnGuardar">Guardar</button>
</div>
</div>
</div>
</div>
<!-- /.modal -->
You could add an eventRender and attach an onClick listener like follow:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
[cut]
eventRender: function (event, element, view) {
element.attr('href', 'javascript:void(0);');
element.click(function() {
$.get( "yoururl/" + event.id, function( data ) {
//Clone object in order to not update the original event (if user press cancel)
var eventClone = deepClone(event);
eventClone.start = data.myStart;
eventClone.end = data.myEnd;
eventClone.title = data.myTitle;
openDialog(eventClone);
});
});
}
[cut]
});
function openDialog(event){
$('#myForm').modal('show');
$('#myModalLabel').html(event.title);
$('#myId').val(event.id);
[cut]
}
So, on you save button (in modal dialog) you could send data to server, save to db and then refresh the calendar like:
$('#calendar').fullCalendar( 'refetchEvents' );
I hope it was clear, bye.
You can add this code:
var calendar = $('#calendar').fullCalendar({
buttonText: {
prev: '<i class="icon-chevron-left"></i>',
next: '<i class="icon-chevron-right"></i>'
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: jQuery.parseJSON(data),
disableDragging: true,
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $extraEventClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
if($extraEventClass) copiedEventObject['className'] = [$extraEventClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
,
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
bootbox.prompt("New Event Title:", function(title) {
if (title !== null) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
});
calendar.fullCalendar('unselect');
}
,
eventClick: function(calEvent, jsEvent, view) {
var form = $("<form class='form-inline'><label>Change event name </label></form>");
form.append("<input autocomplete=off type=text value='" + calEvent.title + "' /> ");
form.append("<button type='submit' class='btn btn-small btn-success'><i class='icon-ok'></i> Save</button>");
var div = bootbox.dialog(form,
[
{
"label" : "<i class='icon-trash'></i> Delete Event",
"class" : "btn-small btn-danger",
"callback": function() {
calendar.fullCalendar('removeEvents' , function(ev){
return (ev._id == calEvent._id);
})
}
}
,
{
"label" : "<i class='icon-remove'></i> Close",
"class" : "btn-small"
}
]
,
{
// prompts need a few extra options
"onEscape": function(){div.modal("hide");}
}
);
form.on('submit', function(){
calEvent.title = form.find("input[type=text]").val();
calendar.fullCalendar('updateEvent', calEvent);
div.modal("hide");
return false;
});
}
});
Add bootbox.min.js to open popup window.
I hope it will work for you!

How can I call second jquery/ajax request?

Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel.
So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.
Can someone suggest me how can I do this ?
Html form code :
<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
$('#success').delay(3000).fadeOut('slow');
</script>
add_contact_process.php page :
<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));
$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);
$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);
$msg = array();
$msg['error'] = false;
if(empty($family_name)){
$msg[] = "<div class='error'>Family name required.</div>";
$msg['error'] = true;
}
if(strlen($given_name) > 30){
$msg[] = "<div class='error'>Given name is too big.</div>";
$msg['error'] = true;
}
// If error is not found
if($msg['error'] === false){
if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
$msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?
<input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>
<input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>
</div>";
$msg['error'] = true;
}else{
$query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
$query_2 = mysqli_query($link, $query_2);
$last_id = mysqli_insert_id($link);
if($query_2){
$msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";
$msg['last_id'] = "$last_id";
$another = "close";
}else{
$msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
$msg[] .= mysqli_error();
$another = "close";
}
}
}
echo json_encode($msg);
?>
Call Second ajax within success
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
/*------------------------------------------------------------------*/
if(confirm('Write your message here')){
/* Second ajax after clicking ok on confirm box */
$.ajax({
url : 'Second URL',
method :'POST',
data : {'data1':data1},
success:function(response){
// code after success
},
error: function(e){
return false;
}
});
}else{
$('#success').hide();
$('#success').hide();
}
/*----------------------------------------------------------*/
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
// some code
},
complete:function () {
//you second ajax call
}

getting state and time of jwplayer

I am trying to get the state and time of the Jwplayer but I get an "undefined" message when trying to see the result of both. I am using Jwplayer 5.7. Please if you can look at my code to see what I have done wrong, that would be awesome. Also my jquery.post() to the database does not fire anything (might be because i am not getting a state). In my console log under networking I cant see the file being called upon.
One final note, I am trying to send the message to the database in a post when the user clicks out of the browser, so far I have not been able to get that to work yet. I think I might be on the right path so please any further guidance would be appreciated.
Thanks in advance.
<?php
$sessionid = 9;
$channelid = 2;
$ipaddress = get_client_ip();
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']) )
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) )
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if( isset($_SERVER['HTTP_X_FORWARDED']) )
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']) )
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']) )
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']) )
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
?>
<!Doctype>
<HTML>
<head>
<!--<link rel="stylesheet" href="css/grid.css" type="text/css">-->
<link rel="stylesheet" href="css/main.css" type="text/css">
<script type="text/javascript"></script>
<!-- Cll on slider.js here -->
</head>
<body>
<!--<div class="side_banner"><img src="images/logo1.png"/></div>-->
<div class="container">
<div class="grid4 omega">
<div class="banner">
<img src="images/banner.png"/>
</div>
<div id="video_container"></div>
<div id="timer"></div>
<div id="state"></div>
</div>
</div>
<script type="text/javascript" src="js/jwplayer.js"></script>
<script type="text/javascript">
jwplayer("video_container").setup({
'modes': [
{type: 'flash', src: 'includes/jwplayer/player.swf'},
{type: 'html5'}
],
'height': 405,
'width': 720,
'autostretch':'false',
'wmode':'transparent',
'controls':false,
'autostart':false,
'file':'<?php echo json_encode($sessionid); ?>.flv',
'repeat':true,
});
var state = jwplayer("video_container").getState();
var time = jwplayer("video_container").getPosition();
document.getElementById('timer').innerHTML = 'The time is ' + time;
document.getElementById('state').innerHTML = 'The player is in a ' + state +' state';
if(state == "PAUSED"){
document.getElementById('timer').innerHTML = 'On pause, the time is ' + time;
}if(state == "IDLE"){
//try to push to database
try{
$.post(
'save_time.php',
{time:time,
ipaddress:<?php echo json_encode($ipaddress);?>,
channelid:<?php echo json_encode($channelid);?>,
sessionid:<?php echo json_encode($sessionid); ?>
},
function data(){
alert(data);
if(data == 'failed'){
alert(failed);
}
}
);
}catch(err){}
}
//take care of the exit
window.onbeforeunload = function(){
console.log('leeeeeeaaavvvving');
//alert('Are you sure you want to close out?');
var formData = {time:time, ipaddress:<?php echo json_encode($ipaddress); ?>, sessionid:<?php echo json_encode($sessionid); ?>, channelid: <?php echo json_encode($channelid); ?>};
$.ajax({
url:'save_time.php',
type:'POST',
data: formData,
async: false,
timeout: 2000,
success: function(data, textStatus, jqXHR)
{
//data - response from server
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('errrororrrrrrr');
}
});
}
</script>
<!--<div class="bottom_buttons">
<div class="button left">Start Over</div>
<div class="button right">Continue</div>
</div>-->
</body>
</html>
I was able to figure this out incase anyone else had the same issue. This is what I did below:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="includes/jwplayer/jwplayer.min.js"></script>
<script type="text/javascript">
//create the general variables
var videoid = <?php echo json_encode($videoid);?>;
var ipaddress = <?php echo json_encode($ipaddress); ?>;
var channelid = <?php echo json_encode($channelid); ?>;
jwplayer("video_container").setup({
'modes': [
{type: 'flash', src: 'includes/jwplayer/player.swf'},
{type: 'html5'}
],
'height': 405,
'width': 720,
'autostretch':'false',
'wmode':'transparent',
'controls':false,
'autostart':false,
'file':'http://content.bitsontherun.com/videos/nPripu9l-60830.mp4',
'repeat':true,
'events': {
onPause :function(){
time = jwplayer("video_container").getPosition();
//get state
browsercloser(time);
},
onBuffer: function(){
time = jwplayer("video_container").getPosition();
browsercloser(time);
},
onPlay :function(){
time = jwplayer("video_container").getPosition();
browsercloser(time);
},
onIdle: function(){
time = jwplayer("video_container").getPosition();
try{
$.post("save_time.php",{time:time, ipaddress:ipaddress, videoid:videoid, channelid:channelid}, function(data){
if(data == 'good'){
alert('We are all good');
}else{
//
alert(failed);
}
});
}catch(err){}
}
}
});
function browsercloser(time){
//take care of the exit incase it happens on play or any other setting
window.onbeforeunload = function(){
console.log('leeeeeeaaavvvving');
//alert('Are you sure you want to close out?');
var formData = {time:time, ipaddress:ipaddress, videoid:videoid, channelid:channelid};
$.ajax({
url:'save_time.php',
type:'POST',
data: formData,
async: false,
timeout: 2000,
success: function(data, textStatus, jqXHR)
{
//data - response from server
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('errrororrrrrrr');
}
});
}
}
</script>
It works on Chrome, Firefox, Internet Explorer and Opera.

Categories

Resources