FullCalendar recurring events array - javascript

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>

Related

How do I submit this wordpress form without page reload?

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;
});

COOKIE created in php is misread in JAVASCRIPT

I have the following problem, I create a cookie in PHP and then read it in javascript and print it and this happens. I do not know how to correct it. Please help.
I read the cookie in javascript:
var micookie = (document.cookie.indexOf('resultado=') === -1 ? '' : ("; " + document.cookie).split('; resultado=')[1].split(';')[0]);
So he created the cookie in PHP:
setcookie("resultado","success",time() + 1, "/kira");
And it prints like this, as you can see in the image
Cerraste+sessi%C3%B3n
Code that creates the notification
var i = -1;
var toastCount = 0;
var $toastlast;
var micookie = (document.cookie.indexOf('resultado=') === -1 ? '' : ("; " + document.cookie).split('; resultado=')[1].split(';')[0]);
var micookietipo = (document.cookie.indexOf('tipo_result=') === -1 ? '' : ("; " + document.cookie).split('; tipo_result=')[1].split(';')[0]);
micookietipo = decodeURIComponent((micookietipo + '').replace(/\+/g, '%20'))
var micookiedesc = (document.cookie.indexOf('desc_result=') === -1 ? '' : ("; " + document.cookie).split('; desc_result=')[1].split(';')[0]);
micookiedesc = decodeURIComponent((micookiedesc + '').replace(/\+/g, '%20'))
function alerta() {
var shortCutFunction = micookie;
var msg = micookiedesc || '';
var title = micookietipo || '';
var $showDuration = $(300);
var $hideDuration = $(1000);
var $timeOut = $(2000);
var $extendedTimeOut = $(500);
var toastIndex = toastCount++;
var addClear = $('#addClear').prop('checked');
toastr.options = {
closeButton: false,
debug: false,
newestOnTop: false,
progressBar: true,
positionClass: 'toast-bottom-right' || 'toast-top-right',
preventDuplicates: true,
onclick: null
};
toastr.options.showEasing = 'swing';
toastr.options.hideEasing = 'linear';
toastr.options.showMethod = 'fadeIn';
toastr.options.hideMethod = 'fadeOut';
var $toast = toastr[shortCutFunction](msg, title); // Wire up an event handler to a button in the toast, if it exists
$toastlast = $toast;
if (typeof $toast === 'undefined') {
return;
}
};
if (typeof micookie !== 'undefined' && typeof micookietipo !== 'undefined' && typeof micookiedesc !== 'undefined') {
alerta();
}
VALIDATE.PHP
<?php
$error = $_COOKIE['resultado'];
if($error == 'error'){
header("location: ../../index.php");
} else {
require_once "../biblioteca.php";
session_start();
$db = ConectaDb($dbHost, $dbUser, $dbPass, $dbName);
$nombre=recoge("nombre");
$email=recoge("email");
$password=recoge("password");
$consulta="SELECT * FROM users WHERE nombre='$nombre' AND email='$email' AND password='$password'";
$result = $db->query($consulta);
if (!$result) {
print "<p>Error en la consulta.</p>\n";
}
elseif ($result->fetchColumn() == 0) {
setcookie("resultado","error",time() + 1, "/kira");
setcookie("tipo_result","Datos incorrectos",time() + 1, "/kira");
setcookie("desc_result","Usuario o contraseña incorrectos",time() + 1, "/kira");
header("Location: ../../index.php");
}
else {
$consulta = "SELECT * FROM users WHERE nombre = '$nombre'";
$result = $db->query($consulta);
if (!$result) {
print " <p>Error en la consulta.</p>\n"; print "\n";
} else {
$consulta = "SELECT * FROM users WHERE nombre = '$nombre'";
$result = $db->query($consulta);
foreach ($result as $valor) {
$tipo_usuario = $valor['tipo_usuario'];
$foto = $valor['foto'];
if($tipo_usuario == "admin"){
setcookie("resultado","success",time() + 1, "/kira");
setcookie("tipo_result","Bienvenido Administrador $nombre",time() + 1, "/kira");
setcookie("desc_result","Has iniciado sessión correctamente",time() + 1, "/kira");
$_SESSION['tipo_user'] = 'administrador';
$_SESSION['usuario'] = $nombre;
$_SESSION['email'] = $email;
$_SESSION['fotoperfil'] = $foto;
$carpeta = '../resources/musica/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/voz/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/luz/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/comida/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/foto/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
header("Location: ../../panelcontrol_admin.php");
return;
}
elseif($tipo_usuario=="user"){
setcookie("resultado","success",time() + 1, "/kira");
setcookie("tipo_result","Bienvenido Usuario $nombre",time() + 1, "/kira");
setcookie("desc_result","Has iniciado sessión correctamente",time() + 1, "/kira");
$_SESSION['tipo_user'] = 'usuario';
$_SESSION['usuario'] = $nombre;
$_SESSION['email'] = $email;
$_SESSION['fotoperfil'] = $foto;
$carpeta = '../resources/musica/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/voz/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/luz/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/comida/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$carpeta = '../resources/foto/'.$nombre;
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
header("Location: ../../panelcontrol_user.php");
return;
}
}
}
}
$db = null;
}
?>
You can decode the string in javascript like so:
var micookie = (document.cookie.indexOf('resultado=') === -1 ? '' : ("; " + document.cookie).split('; resultado=')[1].split(';')[0]);
decodeURIComponent((micookie + '').replace(/\+/g, '%20'))

autocomplete jquery codeigniter error

I'm using Codeigniter with Jquery. I had a problem with jquery Autocomplete. When I enter a keyword, It shows empty list of result.
Controller:
function suggestions()
{
$term = $this->input->get('term', TRUE);
if (strlen($term) < 1) {
die();
}
$rows = $this->products_model->getProductNames($term);
if ($rows) {
foreach ($rows as $row) {
$pr[] = array('id' => $row->id, 'name' => $row->name, 'brand' => $row->brand, 'stock' => $row->stock, 'price' => $row->price, 'hsn' => $row->hsn, 'gst' => $row->gst, 'size' => $row->size);
}
$this->sim->send_json($pr);
}
echo FALSE;
}
Model
public function getProductNames($term, $limit = 5)
{
$this->db->like('brand', $term, 'both');
$this->db->limit($limit);
$q = $this->db->get('products');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
return FALSE;
}
View:
<td>
<div class="input-group">
<?= form_input('product[]', $_POST['product'][$r-1], 'id="product-'.$r.'" class="form-control input-sm suggestions" maxlength="80" style="min-width:270px;"'); ?>
<span class="input-group-addon"><i class="fa fa-file-text-o pointer details"></i></span>
</div>
<div class="details-con details-con-0<?= $r; ?>"<?= $_POST['details'][$r-1] ? '' : ' style="display:none;"'; ?>>
<?= form_textarea('details[]', $_POST['details'][$r-1], 'class="form-control details" id="details-'.$r.'" maxlength="255" style="margin-top:5px;padding:5px 10px;height:60px;"');?>
</div>
</td>
Script:
$(".suggestions").autocomplete({
source: Site.base_url+'products/suggestions',
select: function (event, ui) {
var row = $(this).closest('tr');
var sel_item = ui.item;
row.find('.price').val(sel_item.price);
rate_origin = sel_item.price;
var data = $('#order_tax').val();
var price = parseInt(row.find('.price').val());
if(data == 'incl'){
var gst = parseFloat(price/1.28 * 0.28);
}else{
var gst = parseFloat(price * 0.28);
}
//console.log('THIS IS MAIN PRICE TEST : '+formatDecimal(gst));
row.find('.hsn').val(sel_item.hsn);
row.find('.cgst').val(gst/2);
var igst = $('#gst').val();
if(igst == 'sgst'){
row.find('.igst').val('NIL');
row.find('.sgst').val(gst/2);
}else {
row.find('.sgst').val('NIL');
row.find('.igst').val(gst/2);
}
rate = row.find('.price').val();
var cgst = row.find('.cgst').val();
var sgst = row.find('.sgst').val();
var igst = row.find('.igst').val();
var change_price = 0;
if(data == 'incl'){
if($('#gst').val() === 'sgst'){
change_price = rate / 1.28;
}else {
change_price = rate / 1.28;
}
}else{
if($('#gst').val() === 'sgst'){
change_price = rate;
}else {
change_price = rate;
}
}
row.find('.price').val(change_price);
if(row.find('.sqft').val() == 0){
row.find('.sqft').val(1).change();
}
if (sel_item.brand != '' && sel_item.brand != null) {
row.find('.details-con').css('display', 'block');
row.find('.details').val(sel_item.brand+' - Stock : '+sel_item.stock);
}
calculateTotal();
},
minLength: 1,
autoFocus: false,
delay: 250,
response: function (event, ui) {
if (ui.content.length == 1 && ui.content[0].id != 0) {
ui.item = ui.content[0];
console.log(ui.item.name);
$(this).val(ui.item.name);
$(this).removeClass('ui-autocomplete-loading');
}
},
});
It receives data but it won't show it anymore.I have know idea where the problem is???
Hereby I attached screenshot of my error
Waiting for best answers.Thank you.
Before
Controller:
function suggestions()
{
$term = $this->input->get('term', TRUE);
if (strlen($term) < 1) {
die();
}
$rows = $this->products_model->getProductNames($term);
if ($rows) {
foreach ($rows as $row) {
$pr[] = array('id' => $row->id, 'name' => $row->name, 'brand' => $row->brand, 'stock' => $row->stock, 'price' => $row->price, 'hsn' => $row->hsn, 'gst' => $row->gst, 'size' => $row->size);
}
$this->sim->send_json($pr);
}
echo FALSE;
}
After
function suggestions()
{
$term = $this->input->get('term', TRUE);
if (strlen($term) < 1) {
die();
}
$rows = $this->products_model->getProductNames($term);
if ($rows) {
foreach ($rows as $row) {
$pr[] = array('id' => $row->id, 'label' => $row->name, 'brand' => $row->brand, 'stock' => $row->stock, 'price' => $row->price, 'hsn' => $row->hsn, 'gst' => $row->gst, 'size' => $row->size);
}
$this->sim->send_json($pr);
}
echo FALSE;
}
When we try to get JSON data from PHP or any Server side programming language, we should use a key called label. It should contain a value that shows whenever autocomplete function triggered. So was it shows for me like empty suggestions. Happy coding.

Wordpress Plugin functions, only one works?

So I have a plugin on wordpress with an in-built calendar.
The developer has given instructions on how to remove the option to select past dates, and also specific dates of your choosing.
http://support.themecatcher.net/quform-wordpress/guides/advanced/date-validation
I have followed the instructions, but perhaps I'm missing something. As only one of the functions work at a time, but never both at the same time.
Here is the code. Any help would be greatly appreciated. Thanks!
function my_prevent_past_dates($valid, $value, $element)
{
$time = strtotime("{$value['year']}-{$value['month']}-{$value['day']}");
if ($time < strtotime('today')) {
$element->addError('Please choose a date in the future');
$valid = false;
}
return $valid;
}
add_filter('iphorm_element_valid_iphorm_1_6', 'my_prevent_past_dates', 10, 3);
function my_datepicker_prevent_past_dates($options, $dpMinYear, $dpMaxYear, $element)
{
return "{
minDate: 0,
maxDate: new Date({$dpMaxYear}, 12 - 1, 31)
}";
}
add_filter('iphorm_datepicker_options_iphorm_1_6', 'my_datepicker_prevent_past_dates', 10, 4);
function my_get_dates_to_disable()
{
return array(
'2015-05-1',
'2015-05-2',
'2015-05-3',
'2015-05-4',
'2015-05-5',
'2015-05-6',
);
}
function my_prevent_specific_dates($valid, $value, $element)
{
if ($valid) {
$disabledDates = my_get_dates_to_disable();
$submittedDate = "{$value['year']}-{$value['month']}-{$value['day']}";
if (in_array($submittedDate, $disabledDates)) {
$element->addError('That date is not available');
$valid = false;
}
}
return $valid;
}
add_filter('iphorm_element_valid_iphorm_1_6', 'my_prevent_specific_dates', 10, 3);
function my_datepicker_prevent_specific_dates($options, $dpMinYear, $dpMaxYear, $element)
{
return "{
beforeShowDay: function (date) {
if (quformDisabledDates) {
for (var i = 0; i < quformDisabledDates.length; i++) {
var parts = quformDisabledDates[i].split('-');
if (date.getFullYear() == parts[0] && (date.getMonth()+1) == parts[1] && date.getDate() == parts[2]) {
return [false];
}
}
}
return [true];
}
}";
}
add_filter('iphorm_datepicker_options_iphorm_1_6', 'my_datepicker_prevent_specific_dates', 10, 4);
function my_print_dates_to_disable()
{
?>
<script type="text/javascript">
var quformDisabledDates = <?php echo json_encode(my_get_dates_to_disable()); ?>;
</script>
<?php
}
add_action('wp_head', 'my_print_dates_to_disable');
You can combine my_prevent_past_dates with my_prevent_specific_dates, and my_datepicker_prevent_past_dates with my_datepicker_prevent_specific_dates.
function my_get_dates_to_disable()
{
return array(
'2015-05-1',
'2015-05-2',
'2015-05-3',
'2015-05-4',
'2015-05-5',
'2015-05-6',
);
}
function my_prevent_bad_dates($valid, $value, $element)
{
$time = strtotime("{$value['year']}-{$value['month']}-{$value['day']}");
if ($time < strtotime('today')) {
$element->addError('Please choose a date in the future');
$valid = false;
} else {
$disabledDates = my_get_dates_to_disable();
$submittedDate = "{$value['year']}-{$value['month']}-{$value['day']}";
if (in_array($submittedDate, $disabledDates)) {
$element->addError('That date is not available');
$valid = false;
}
}
return $valid;
}
add_filter('iphorm_element_valid_iphorm_1_6', 'my_prevent_bad_dates', 10, 3);
function my_datepicker_prevent_bad_dates($options, $dpMinYear, $dpMaxYear, $element)
{
return "{
minDate: 0,
maxDate: new Date({$dpMaxYear}, 12 - 1, 31),
beforeShowDay: function (date) {
if (quformDisabledDates) {
for (var i = 0; i < quformDisabledDates.length; i++) {
var parts = quformDisabledDates[i].split('-');
if (date.getFullYear() == parts[0] && (date.getMonth()+1) == parts[1] && date.getDate() == parts[2]) {
return [false];
}
}
}
return [true];
}
}";
}
add_filter('iphorm_datepicker_options_iphorm_1_6', 'my_datepicker_prevent_bad_dates', 10, 4);
function my_print_dates_to_disable()
{
?>
<script type="text/javascript">
var quformDisabledDates = <?php echo json_encode(my_get_dates_to_disable()); ?>;
</script>
<?php
}
add_action('wp_head', 'my_print_dates_to_disable');

Ways to improve the speed / efficiency of my jquery / ajax / php call?

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;
}
}

Categories