So basically I need to submit this quick-interest-slider form without page reload - https://loancalc.000webhostapp.com , this isn't my code, i'm not too experienced with wordpress or php.
After adding this $('.qis-form').on('submit'... code the slider continues to reload the page once i've clicked "apply now".
I don't know exactly what in the code I should be working with but i'm told the functions are...
qis-loop (validates and processes the form), qis_process_form also processes the form and sends email.
function qis_loop($atts) {
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
qis_process_form
function qis_process_form($values) {
global $post;
$content='';
$register = qis_get_stored_register($values['formname']);
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$qis_messages = get_option('qis_messages');
$application = qis_get_stored_application_messages();
if(!is_array($qis_messages)) $qis_messages = array();
$ip=$_SERVER['REMOTE_ADDR'];
$url = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
$page = get_the_title();
if (empty($page)) $page = 'Unknown Page';
$period = $values['loan-period'] == 1 ? $settings['singleperiodlabel'] : $settings['periodlabel'];
if (!$period) $period = $settings['period'];
$values['loan-amount'] = $settings['currency'].$values['loan-amount'];
$values['loan-period'] = $values['loan-period'].' '.$period;
$radio = explode(',',$register['radiolist']);
$values['yourradio'] = $radio[$values['radiooption']];
for ($i=1;$i<=3;$i++) {
if ($values['check'.$i]) $checks .= $register['check'.$i] . '<br>';
}
if ($checks) $values['yourchecks'] .= substr($checks, 0, -4);
$values['sentdate'] = date_i18n('d M Y');
$values['timestamp'] = time();
if ($register['storedata']) {
$newmessage = array();
$arr = array(
'reference',
'yourname',
'youremail',
'yourtelephone',
'yourmessage',
'yourchecks',
'yourradio',
'yourdropdown',
'yourconsent',
'loan-amount',
'loan-period',
'confirmation',
'formname',
'sentdate',
'timestamp'
);
foreach ($arr as $item) {
if ($values[$item] != $register[$item]) $newmessage[$item] = $values[$item];
}
$qis_messages[] = $newmessage;
update_option('qis_messages',$qis_messages);
}
if (!$auto['notification']) {
qis_send_notification ($values);
}
if (($auto['enable'] || $values['qis-copy']) && !$application['enable']) {
qis_send_confirmation ($auto,$values,$content,$register);
}
if ($register['qis_redirect_url']) {
$location = $register['qis_redirect_url'];
echo "<meta http-equiv='refresh' content='0;url=$location' />";
exit;
}}
The data is validated in qis_verify_application
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
If it passes validation the form is then processed in qis_process_application.
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
I have made an ajax call here
jQuery('.qis-form').on('submit', function(event){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
After hunting down your html, you will want to call it on the APPLY click NOT form submit.
jQuery(document).on('click','.toggle-qis a', function(event){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
return false;
});
I have this Js file and i want to implement Php request for sending message , history,update but nothing,i'm new with this, please help me.
The chat can be viewed here: http://demo.neontheme.com/extra/chat-api/
Db structure is: id | from | fromOpponent | message | time |unread
The js file:
var neonChat = neonChat || {
$current_user: null,
isOpen: false,
chat_history: [],
statuses: {
online: {class: 'is-online', order: 1, label: 'Online'},
offline: {class: 'is-offline', order: 4, label: 'Offline'},
idle: {class: 'is-idle', order: 3, label: 'Idle'},
busy: {class: 'is-busy', order: 2, label: 'Busy'}
}
};
;(function($, window, undefined)
{
"use strict";
var $chat = $("#chat"),
$chat_inner = $chat.find('.chat-inner'),
$chat_badge = $chat.find('.badge').add($('.chat-notifications-badge')),
$conversation_window = $chat.find(".chat-conversation"),
$conversation_header = $conversation_window.find(".conversation-header"),
$conversation_body = $conversation_window.find('.conversation-body'),
$textarea = $conversation_window.find('.chat-textarea textarea'),
sidebar_default_is_open = ! $(".page-container").hasClass('sidebar-collapsed');
$.extend(neonChat, {
init: function()
{
// Conversation Close
$conversation_window.on('click', '.conversation-close', neonChat.close);
$("body").on('click', '.chat-close', function(ev)
{
ev.preventDefault();
var animate = $(this).is('[data-animate]');
neonChat.hideChat(animate);
});
$("body").on('click', '.chat-open', function(ev)
{
ev.preventDefault();
var animate = $(this).is('[data-animate]');
neonChat.showChat(animate);
});
// Texarea
$textarea.keydown(function(e)
{
if(e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
neonChat.submitMessage();
return false;
}
else
if(e.keyCode == 27)
{
neonChat.close();
}
});
$chat.on('click', '.chat-group a', function(ev)
{
ev.preventDefault();
var $chat_user = $(this);
if($chat_user.hasClass('active'))
{
neonChat.close();
}
else
{
neonChat.open($chat_user);
}
});
$chat.find('.chat-group a').each(function(i, el)
{
var $this = $(el);
$this.append('<span class="badge badge-info is-hidden">0</span>');
});
neonChat.refreshUserIds();
neonChat.orderGroups();
neonChat.prefetchMessages();
neonChat.countUnreadMessages();
neonChat.puffUnreads();
// Chat
if($chat.hasClass('fixed') && $chat_inner.length && $.isFunction($.fn.niceScroll))
{
$chat.find('.chat-inner').niceScroll({
cursorcolor: '#454a54',
cursorborder: '1px solid #454a54',
railpadding: {right: 3},
railalign: 'right',
cursorborderradius: 1
});
}
// Chat Toggle
$("body").on('click', '[data-toggle="chat"]', function(ev)
{
ev.preventDefault();
var $this = $(this),
with_animation = $this.is('[data-animate]'),
collapse_sidebar = $this.is('[data-collapse-sidebar]');
neonChat.toggleChat(with_animation, collapse_sidebar);
});
},
updateConversationOffset: function($el)
{
var top_h = $conversation_window.find('.conversation-body').position().top + 1,
offset = $el.position().top - top_h,
minus = 0,
con_h = $conversation_window.height(),
win_h = $(window).height();
if($chat.hasClass('fixed') && offset + con_h > win_h)
{
minus = offset + con_h - win_h;
}
if($(".page-container.horizontal-menu").length)
{
minus += $(".page-container.horizontal-menu .navbar").height();
}
offset -= minus;
$conversation_window.transition({
top: offset,
opacity: 1
});
},
getChatHistoryLength: function()
{
var max_chat_history = parseInt($chat.data('max-chat-history'), 10);
if( ! max_chat_history || max_chat_history < 1)
{
max_chat_history = 25;
}
return max_chat_history;
},
submitMessage: function() // Submit whats on textarea
{
var msg = $.trim($textarea.val());
$textarea.val('');
if(this.isOpen && this.$current_user)
{
var id = this.$current_user.uniqueId().attr('id');
this.pushMessage(id, msg.replace( /<.*?>/g, '' ), $chat.data('current-user'), new Date());
this.renderMessages(id);
}
},
refreshUserIds: function()
{
$('#chat .chat-group a').each(function(i, el)
{
var $this = $(el),
$status = $this.find('.user-status');
$this.uniqueId();
var id = $this.attr('id');
if(typeof neonChat.chat_history[id] == 'undefined')
{
var status = $this.data('status');
if( ! status)
{
for(var i in neonChat.statuses)
{
if($status.hasClass(neonChat.statuses[i].class))
{
status = i;
break;
}
}
}
neonChat.chat_history[id] = {
$el: $this,
messages: [],
unreads: 0,
status: status
};
}
});
},
pushMessage: function(id, msg, from, time, fromOpponent, unread)
{
if(id && msg)
{
this.refreshUserIds();
var max_chat_history = this.getChatHistoryLength();
if(this.chat_history[id].messages.length >= max_chat_history)
{
this.chat_history[id].messages = this.chat_history[id].messages.reverse().slice(0, max_chat_history - 1).reverse();
}
this.chat_history[id].messages.push({
message: msg,
from: from,
time: time,
fromOpponent: fromOpponent,
unread: unread
});
if(unread)
{
this.puffUnreadsAll();
}
this.puffUnreads();
}
},
renderMessages: function(id, slient)
{
if(typeof this.chat_history[id] != 'undefined')
{
$conversation_body.html('');
for(var i in this.chat_history[id].messages)
{
var entry = this.chat_history[id].messages[i],
$entry = $('<li><span class="user"></span><p></p><span class="time"></span></li>'),
date = entry.time,
date_formated = date;
if(typeof date == 'object')
{
var hour = date.getHours(),
hour = (hour < 10 ? "0" : "") + hour,
min = date.getMinutes(),
min = (min < 10 ? "0" : "") + min,
sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
date_formated = hour + ':' + min;
}
// Populate message DOM
$entry.find('.user').html(entry.from);
$entry.find('p').html(entry.message.replace(/\n/g, '<br>'));
$entry.find('.time').html(date_formated);
if(entry.fromOpponent)
{
$entry.addClass('odd');
}
if(entry.unread && typeof slient == 'undefined')
{
$entry.addClass('unread');
entry.unread = false;
}
$conversation_body.append($entry);
}
this.updateScrollbars();
}
},
prefetchMessages: function()
{
$chat.find('.chat-group a').each(function(i, el)
{
var $contact = $(el),
id = $contact.attr('id'),
history_container = $contact.data('conversation-history');
if(history_container && history_container.length)
{
$($(history_container)).find('> li').each(function(j, el2)
{
var $entry = $(el2),
from = $entry.find('.user').html(),
message = $entry.find('p').html(),
time = $entry.find('.time').html(),
fromOpponent = $entry.hasClass('even') || $entry.hasClass('odd') || $entry.hasClass('opponent'),
unread = $entry.hasClass('unread');
neonChat.pushMessage(id, message, from, time, fromOpponent, unread)
});
}
});
},
// Set Cursor
$conversation_body.on('click', function()
{
$textarea.focus();
});
// Refresh Ids
neonChat.init();
})(jQuery, window);
What i have trying to implement but failed:
function sendChat(id, msg, from, time, fromOpponent, unread) {
$.ajax({
type: "POST",
url: "process.php",
data: {'function': 'from','message': message,'fromOpponent': id,'unread': unread},
dataType: "json",
success: function(data){
}
});
The Php/Html code:
<div id="chat" class="fixed" data-current-user="<?php echo $user->filter->username;?>" data-order-by-status="1" data-max-chat-history="25">
<?php
$conn = new PDO('mysql:host=localhost;dbname=testest', 'user', 'pass');
$sqlb = "SELECT * FROM `mls_users`";
$userz = $conn->query($sqlb);
foreach ($userz as $row) {
$name= $row['name'];
$surename = $row['surename'];
$status = $row['statusonline'];
$id = $row['id'];
echo "<a href='#' data-conversation-history='#sample_history_".$id."' id='$id'><span class='user-status is-".$status."line'></span> <em>$name $surename</em></a>";
}
?>
</div>
<!-- conversation template -->
<div class="chat-conversation">
<div class="conversation-header">
<i class="entypo-cancel"></i>
<span class="user-status"></span>
<span class="display-name"></span>
<small></small>
</div>
<ul class="conversation-body">
</ul>
<div class="chat-textarea">
<textarea class="form-control autogrow" placeholder="Type your message"></textarea>
</div>
</div>
</div>
<?php
$con = new PDO('mysql:host=localhost;dbname=chat', 'user', 'pass');
$sqlb = "SELECT * FROM `messages` ";
$userr = $con->query($sqlb);
foreach ($userr as $row) {
$from= $row['from'];
$fromOpponent = $row['fromOpponent'];
}
?>
<!-- Chat Histories -->
<?php
$conn = new PDO('mysql:host=localhost;dbname=chat', 'user', 'pass');
$sqlb = "SELECT TIME_FORMAT(time, '%H:%i') as `time`,`id`,`name`,`surename`,`message`,`unread`,`from`,`fromOpponent` FROM `message` WHERE `from`='$from' AND `fromOpponent`='$fromOpponent'";
$userz = $conn->query($sqlb);
foreach ($userz as $row) {
$id = $row['id'];
$from= $row['from'];
$fromOpponent= $row['fromOpponent'];
$name= $row['name'];
$surename= $row['surname'];
$message = $row['messagee'];
$time= $row['time'];
$unread = $row['unread'];
echo "<ul class='chat-history' id='sample_history_$from'>
<li class='opponent $unread'>
<span class='user'>$name $surename</span>
<p>$message</p>
<span class='time'>$time</span>";
}
?>
</li>
</ul>
</div>
I'm working on a recurring events backend for fullcalendar, and I've run into a strange problem.
My events are calculated on a page called events.php. The calendar is displayed on index.php and calls the events from events.php. My function on events.php outputs the correct string for the recurring events, but the calendar on index.php only displays the first event in each recurrence. However, if I copy the string that the array produces and paste it directly into the events.php page and comment out the render_fccalendar_events(); function and inthe end of events.php that produces the string, the calendar will display all of the recurring events correctly. From what I can see the output of the function, and what I'm pasting into the page are feeding the calendar on index.php exactly the same thing. Obviously there is some difference though because it's not rendering them the same. Any idea what in the world is going on here?
This is the events.php code:
<?php require_once('../../Connections/local_i.php');
require_once('../../webassist/mysqli/rsobj.php');
global $wpdb;
$wpdb = new WA_MySQLi_RS("wpdb",$local_i,0);
$wpdb->setQuery("SELECT wpdb.id, wpdb.location, wpdb.name, wpdb.description, wpdb.recurrence, wpdb.start_date, wpdb.end_date, wpdb.repeat, wpdb.repeat_desk, wpdb.occurrence, wpdb.occurrence_desk FROM wpdb");
$wpdb->execute();
ini_set('display_errors', '0');
function render_fccalendar_events() {
$_POST['start'] = (isset($_POST['start']) ? $_POST['start'] : strtotime('2014-09-01'));
$_POST['end'] = (isset($_POST['end']) ? $_POST['end'] : strtotime('2014-09-30'));
$start = date('Y-m-d',$_POST['start']);
$end = date('Y-m-d', $_POST['end']);
$readonly = (isset($_POST['readonly'])) ? true : false;
$events = fcdb_query_events($start, $end);
render_json(process_events($events, $start, $end, $readonly));
}
function process_events($events, $start, $end, $readonly) {
if ($events) {
$output = array();
foreach ($events as $event) {
$event->view_start = $start;
$event->view_end = $end;
$event = process_event($event, $readonly, true);
if (is_array($event)) {
foreach ($event as $repeat) {
array_push($output, $repeat);
}
} else {
array_push($output, $event);
}
}
return $output;
}
}
function process_event($input, $readonly = false, $queue = false) {
$output = array();
if ($repeats = generate_repeating_event($input)) {
foreach ($repeats as $repeat) {
array_push($output, generate_event($repeat));
}
} else {
array_push($output, generate_event($input));
}
if ($queue) {
return $output;
}
render_json($output);
}
function generate_event($input) {
$output = array(
'id' => $input->id,
'title' => $input->name,
'start' => $input->start_date,
'end' => $input->end_date,
'allDay' => ($input->allDay) ? true : false,
//'className' => "cat{$repeats}",
'editable' => true,
'repeat_i' => $input->repeat_int,
'repeat_f' => $input->repeat_freq,
'repeat_e' => $input->repeat_end
);
return $output;
}
function generate_repeating_event($event) {
$repeat_desk = json_decode($event->repeat_desk);
if ($event->repeat == "daily") {
$event->repeat_int =0;
$event->repeat_freq = $repeat_desk->every_day;
}
if ($event->repeat == "monthly") {
$event->repeat_int =2;
$event->repeat_freq = $repeat_desk->every_month;
}
if ($event->repeat == "weekly") {
$event->repeat_int =1;
$event->repeat_freq = $repeat_desk->every_week;
}
if ($event->repeat == "year") {
$event->repeat_int =3;
$event->repeat_freq = $repeat_desk->every_year;
}
if ($event->occurrence == "after-no-of-occurrences") {
if($event->repeat_int == 0){
$ext = "days";
}
if($event->repeat_int == 1){
$ext = "weeks";
}
if($event->repeat_int == 2){
$ext = "months";
}
if($event->repeat_int == 3){
$ext = "years";
}
$event->repeat_end = date('Y-m-d',strtotime("+" . $event->repeat_int . " ".$ext));
} else if ($event->occurrence == "no-end-date") {
$event->repeat_end = "2023-04-13";
} else if ($event->occurrence == "end-by-end-date") {
$event->repeat_end = $event->end_date;
}
if ($event->repeat_freq) {
$event_start = strtotime($event->start_date);
$event_end = strtotime($event->end_date);
$repeat_end = strtotime($event->repeat_end) + 86400;
$view_start = strtotime($event->view_start);
$view_end = strtotime($event->view_end);
$repeats = array();
while ($event_start < $repeat_end) {
if ($event_start >= $view_start && $event_start <= $view_end) {
$event = clone $event; // clone event details and override dates
$event->start_date = date('Y-m-d', $event_start);
$event->end_date = date('Y-m-d', $event_end);
array_push($repeats, $event);
}
$event_start = get_next_date($event_start, $event->repeat_freq, $event->repeat_int);
$event_end = get_next_date($event_end, $event->repeat_freq, $event->repeat_int);
}
return $repeats;
}
return false;
}
function get_next_date($date, $freq, $int) {
if ($int == 0)
return strtotime("+" . $freq . " days", $date);
if ($int == 1)
return strtotime("+" . $freq . " weeks", $date);
if ($int == 2)
return get_next_month($date, $freq);
if ($int == 3)
return get_next_year($date, $freq);
}
function get_next_month($date, $n = 1) {
$newDate = strtotime("+{$n} months", $date);
// adjustment for events that repeat on the 29th, 30th and 31st of a month
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 1 . " months", $date);
}
return $newDate;
}
function get_next_year($date, $n = 1) {
$newDate = strtotime("+{$n} years", $date);
// adjustment for events that repeat on february 29th
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 3 . " years", $date);
}
return $newDate;
}
function render_json($output) {
header("Content-Type: application/json");
echo json_encode(cleanse_output($output));
exit;
}
function cleanse_output($output) {
if (is_array($output)) {
array_walk_recursive($output, create_function('&$val', '$val = trim(stripslashes($val));'));
} else {
$output = stripslashes($output);
}
return $output;
}
function fcdb_query_events($start, $end) {
global $wpdb;
$result = array();
// $limit = ($limit) ? " LIMIT {$limit}" : "";
while(!$wpdb->atEnd()) {
$item = new stdClass;
$item->id = $wpdb->getColumnVal('id');
$item->location = $wpdb->getColumnVal('location');
$item->name = $wpdb->getColumnVal('name');
$item->description = $wpdb->getColumnVal('description');
$item->recurrence = $wpdb->getColumnVal('recurrence');
$item->start_date = $wpdb->getColumnVal('start_date');
$item->end_date = $wpdb->getColumnVal('end_date');
$item->repeat = $wpdb->getColumnVal('repeat');
$item->repeat_desk = $wpdb->getColumnVal('repeat_desk');
$item->occurrence = $wpdb->getColumnVal('occurrence');
$item->occurrence_desk = $wpdb->getColumnVal('occurrence_desk');
$item->allDay = false;
$result[] = $item;
$wpdb->moveNext();
}
$wpdb->moveFirst(); //return RS to first record
return return_result($result);
}
function return_result($result) {
if ($result === false) {
global $wpdb;
$this->log($wpdb->print_error());
return false;
}
return $result;
}
render_fccalendar_events();?>
This is the output of the events.php page
[{"id":"1","title":"test event","start":"2014-09-01","end":"2014-09-01","allDay":"","editable":"1","repeat_i":"1","repeat_f":"3","repeat_e":"2023-04-13"},{"id":"1","title":"test event","start":"2014-09-22","end":"2014-09-22","allDay":"","editable":"1","repeat_i":"1","repeat_f":"3","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-04","end":"2014-09-04","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-06","end":"2014-09-06","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-08","end":"2014-09-08","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-10","end":"2014-09-10","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-12","end":"2014-09-12","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-14","end":"2014-09-14","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-16","end":"2014-09-16","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-18","end":"2014-09-18","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-20","end":"2014-09-20","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-22","end":"2014-09-22","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-24","end":"2014-09-24","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-26","end":"2014-09-26","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-28","end":"2014-09-28","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"3","title":"test 2","start":"2014-10-04 13:00:00","end":"2014-10-04 14:00:00","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"}]
This is the index.php code that's calling the events.php output:
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '<?php echo date('Y-m-d'); ?>',
editable: true,
events: {
url: 'events.php',
type: 'POST'
},
error: function() {
alert('there was an error while fetching events!');
}
});
});
</script>
This seemed to work.
<?php require_once('../../Connections/local_i.php');
require_once('../../webassist/mysqli/rsobj.php');
global $wpdb;
$wpdb = new WA_MySQLi_RS("wpdb",$local_i,0);
$wpdb->setQuery("SELECT wpdb.id, wpdb.location, wpdb.name, wpdb.description, wpdb.recurrence, wpdb.start_date, wpdb.end_date, wpdb.repeat, wpdb.repeat_desk, wpdb.occurrence, wpdb.occurrence_desk, wpdb.repeat_key FROM wpdb");
$wpdb->execute();
ini_set('display_errors', '0');
function render_fccalendar_events() {
//$_POST['start'] = (isset($_POST['start']) ? strtotime($_POST['start']) : strtotime('2014-09-01'));
// $_POST['end'] = (isset($_POST['end']) ? strtotime($_POST['end']) : strtotime('2014-09-30'));
$_POST['start'] = strtotime($_POST['start']);
$_POST['end'] = strtotime($_POST['end']);
$start = date('Y-m-d',$_POST['start']);
$end = date('Y-m-d', $_POST['end']);
$readonly = (isset($_POST['readonly'])) ? true : false;
$events = fcdb_query_events($start, $end);
render_json(process_events($events, $start, $end, $readonly));
}
function process_events($events, $start, $end, $readonly) {
if ($events) {
$output = array();
foreach ($events as $event) {
$event->view_start = $start;
$event->view_end = $end;
$event = process_event($event, $readonly, true);
if (is_array($event)) {
foreach ($event as $repeat) {
array_push($output, $repeat);
}
} else {
array_push($output, $event);
}
}
return $output;
}
}
function process_event($input, $readonly = false, $queue = false) {
$output = array();
if ($repeats = generate_repeating_event($input)) {
foreach ($repeats as $repeat) {
array_push($output, generate_event($repeat));
}
} else {
array_push($output, generate_event($input));
}
if ($queue) {
return $output;
}
render_json($output);
}
function generate_event($input) {
$output = array(
'id' => $input->id,
'title' => $input->name,
'start' => $input->start_date,
'end' => $input->end_date,
'allDay' => ($input->allDay) ? true : false,
//'className' => "cat{$repeats}",
'editable' => true,
'repeat_i' => $input->repeat_int,
'repeat_f' => $input->repeat_freq,
'repeat_e' => $input->repeat_end
);
return $output;
}
function generate_repeating_event($event) {
$repeat_desk = json_decode($event->repeat_desk);
if ($event->repeat == "daily") {
$event->repeat_int =0;
$event->repeat_freq = $repeat_desk->every_day;
}
if ($event->repeat == "monthly") {
$event->repeat_int =2;
$event->repeat_freq = $repeat_desk->every_month;
}
if ($event->repeat == "weekly") {
$event->repeat_int =1;
$event->repeat_freq = $repeat_desk->every_week;
}
if ($event->repeat == "year") {
$event->repeat_int =3;
$event->repeat_freq = $repeat_desk->every_year;
}
if ($event->occurrence == "after-no-of-occurrences") {
if($event->repeat_int == 0){
$ext = "days";
}
if($event->repeat_int == 1){
$ext = "weeks";
}
if($event->repeat_int == 2){
$ext = "months";
}
if($event->repeat_int == 3){
$ext = "years";
}
$event->repeat_end = date('Y-m-d',strtotime("+" . $event->repeat_int . " ".$ext));
} else if ($event->occurrence == "no-end-date") {
$event->repeat_end = "2023-04-13";
} else if ($event->occurrence == "end-by-end-date") {
$event->repeat_end = $event->end_date;
}
if ($event->repeat_freq) {
// explode skipped events string (from database) into array $list_of_skipped_events
$event_start = strtotime($event->start_date);
$event_end = strtotime($event->end_date);
$repeat_end = strtotime($event->repeat_end) + 86400;
$view_start = strtotime($event->view_start);
$view_end = strtotime($event->view_end);
$repeats = array();
$counter = 1;
while ($event_start < $repeat_end) {
if ($event_start >= $view_start && $event_start <= $view_end) {
$event = clone $event; // clone event details and override dates
$event->start_date = date('Y-m-d', $event_start);
$event->end_date = date('Y-m-d', $event_end);
//if counter is in list of events to skip, don't do the next line
//if(! in_array($counter, $list_of_skipped_events))
array_push($repeats, $event);
}
$event_start = get_next_date($event_start, $event->repeat_freq, $event->repeat_int);
$event_end = get_next_date($event_end, $event->repeat_freq, $event->repeat_int);
$counter++;
}
return $repeats;
}
return false;
}
function get_next_date($date, $freq, $int) {
if ($int == 0)
return strtotime("+" . $freq . " days", $date);
if ($int == 1)
return strtotime("+" . $freq . " weeks", $date);
if ($int == 2)
return get_next_month($date, $freq);
if ($int == 3)
return get_next_year($date, $freq);
}
function get_next_month($date, $n = 1) {
$newDate = strtotime("+{$n} months", $date);
// adjustment for events that repeat on the 29th, 30th and 31st of a month
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 1 . " months", $date);
}
return $newDate;
}
function get_next_year($date, $n = 1) {
$newDate = strtotime("+{$n} years", $date);
// adjustment for events that repeat on february 29th
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 3 . " years", $date);
}
return $newDate;
}
function render_json($output) {
header("Content-Type: application/json");
echo json_encode(cleanse_output($output));
exit;
}
function cleanse_output($output) {
if (is_array($output)) {
array_walk_recursive($output, create_function('&$val', '$val = trim(stripslashes($val));'));
} else {
$output = stripslashes($output);
}
return $output;
}
function fcdb_query_events($start, $end) {
global $wpdb;
$result = array();
// $limit = ($limit) ? " LIMIT {$limit}" : "";
while(!$wpdb->atEnd()) {
$item = new stdClass;
$item->id = $wpdb->getColumnVal('id');
$item->location = $wpdb->getColumnVal('location');
$item->name = $wpdb->getColumnVal('name');
$item->description = $wpdb->getColumnVal('description');
$item->recurrence = $wpdb->getColumnVal('recurrence');
$item->start_date = $wpdb->getColumnVal('start_date');
$item->end_date = $wpdb->getColumnVal('end_date');
$item->repeat = $wpdb->getColumnVal('repeat');
$item->repeat_desk = $wpdb->getColumnVal('repeat_desk');
$item->occurrence = $wpdb->getColumnVal('occurrence');
$item->occurrence_desk = $wpdb->getColumnVal('occurrence_desk');
$item->allDay = false;
$result[] = $item;
$wpdb->moveNext();
}
$wpdb->moveFirst(); //return RS to first record
return return_result($result);
}
function return_result($result) {
if ($result === false) {
global $wpdb;
$this->log($wpdb->print_error());
return false;
}
return $result;
}
render_fccalendar_events();?>
and
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '<?php echo date('Y-m-d'); ?>',
editable: true,
events: {
url: 'events.php',
type: 'POST'
},
error: function() {
alert('there was an error while fetching events!');
}
});
});
</script>
I have a table with 80 articles in it, I have a checkbox for each article.
I have code (AJAX, PHP) to activate / deactivate the articles in bulk while checkboxes are checked.
I am finding my ajax call takes 2+ seconds to activate / deactivate all 80 records, this seems slow, can you see a way to improve my code?
All help appreciated!
Here is my Jquery / Ajax:
$(document).on("click",".applybtn",function() {
// GET SELECTOR
var selector = $("#selector").attr("name");
// GET OPTIONS
var option = $("#control").val();
var option2 = $("#control2").val();
if($(".idcheck").is(":checked")) {
// GET CHECKBOXS
var val = [];
$(".idcheck:checked").each(function(i) {
val[i] = $(this).val();
});
if(selector === 'article' || selector === 'articlecats') {
$.ajax({
type: "POST",
url: "controllers/articlecontrol.php",
data: { id: val, option: option, option2: option2, selector: selector },
success: function(data){
if(option == 'delete' || option2 == 'delete') {
$(".idcheck:checked").each(function() {
$(this).closest("tr").remove();
})
}
if(option == 'activate' || option2 == 'activate' || option == 'deactivate' || option2 == 'deactivate') {
document.location.reload(true);
}
$('.successmessage').html(data).fadeIn("fast").fadeOut(3000);
if($('.select-all').is(':checked')) {
$('.select-all').prop('checked', false);
}
}
});
return false;
}
}
else {
$('.errormessage').html("<div class='error'>Please Make Your Selection<\/div>").fadeIn("fast").fadeOut(3000);
}
});
Here is my PHP:
if (isset($_POST['option']) || isset($_POST['option2'])) {
// MULTI ACTIVATE ARTICLE
if ($selector === 'article' && $option === 'activate' || $option2 === 'activate') {
$id = $id;
foreach($id as $val) {
$update = array('article_active' => '1');
$where = array('article_id' => $val);
$sql = $database->update('wcx_articles', $update, $where);
}
if ($sql) {
echo '<div class="success">Article(s) Activated Successfully</div>';
}
else {
echo '<div class="error">There was a problem Activating the Article(s) with ID'.$id.'</div>';
}
}
// MULTI DEACTIVATE ARTICLE
if ($selector === 'article' && $option === 'deactivate' || $option2 === 'deactivate') {
$id = $id;
foreach($id as $val) {
$update = array('article_active' => '0');
$where = array('article_id' => $val);
$sql = $database->update('wcx_articles', $update, $where);
}
if ($sql) {
echo '<div class="success">Article(s) Deactivated Successfully</div>';
}
else {
echo '<div class="error">There was a problem Deactivating the Article(s) with ID'.$id.'</div>';
}
}
}
I'm using a custom mysqli wrapper to make the calls to DB:
// UPDATE TABLE
public function update( $table, $variables = array(), $where = array(), $limit = '' ) {
$sql = "UPDATE ". $table ." SET ";
foreach( $variables as $field => $value ) {
$updates[] = "`$field` = '$value'";
}
$sql .= implode(', ', $updates);
foreach( $where as $field => $value ) {
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
if( !empty( $limit ) ) {
$sql .= ' LIMIT '. $limit;
}
$query = mysqli_query( $this->link, $sql );
if( mysqli_error( $this->link ) ) {
$this->log_db_errors( mysqli_error( $this->link ), $sql, 'Fatal' );
return false;
}
else {
return true;
}
}
It looks like you're performing a single SQL update query for each article you're updating. Consider changing your PHP script so that you perform a single update for multiple articles.
Instead of generating SQL like this:
UPDATE wcx_articles SET article_active = 1 WHERE article_id = 123;
UPDATE wcx_articles SET article_active = 1 WHERE article_id = 456;
UPDATE wcx_articles SET article_active = 1 WHERE article_id = 789;
Performing one single update would likely be more efficient:
UPDATE wcx_articles SET article_active = 1 WHERE article_id IN (123, 456, 789);
That would be a decent starting point for improving efficiency of your code.
UPDATED
PHP
// MULTI ACTIVATE ARTICLE
if ($selector === 'article' && $option === 'activate' || $option2 === 'activate') {
$id = $id;
$update = "1";
$where = implode(',',$id);
$sql = $database->articleADUpdate('wcx_articles', $update, $where);
if ($sql) {
echo '<div class="success">Article(s) Activated Successfully</div>';
}
else {
echo '<div class="error">There was a problem Activating the Article(s) with ID'.$id.'</div>';
}
}
public function articleADUpdate($table, $variables, $where) {
$sql = "UPDATE wcx_articles SET article_active =".$variables." WHERE article_id IN ($where)";
if( !empty( $limit ) ) {
$sql .= ' LIMIT '. $limit;
}
$query = mysqli_query( $this->link, $sql );
if( mysqli_error( $this->link ) ) {
$this->log_db_errors( mysqli_error( $this->link ), $sql, 'Fatal' );
return false;
}
else {
return true;
}
}