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

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

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

Ajax call result not working properly

I have this function where on onkeyup it verifies the mobile number whether it exists in the database already or not now the issue is even if the response is "true" it will always show as false
PHP
elseif ($action == 'check_mobile_phone')
{
$mobile = trim($_GET['mobile']);
$mobile = json_str_iconv($mobile);
if (mobile_register($mobile))
{
echo 'false';
}
else
{
echo 'true';
}
}
Ajax Call
function checkMobilePhone(mobile)
{
if (mobile == '')
{
error.find('#mobile_notice_text').html('Mobile number cant be empty.');
submit_disabled = true;
}
else if (!Utils.isMobile(mobile))
{
error.find('#mobile_notice_text').html('Please enter mobile number in local format.');
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_mobile_phone', 'mobile=' + mobile, check_mobile_callback , 'GET', 'TEXT', true, true );
}
Response
function check_mobile_callback(result)
{
var logform = $('form[name="formUser"]');
var error = logform.find('#mobile_notice');
if ( result === "true" )
{
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
error.find('#mobile_notice_text').html('Phone number already exists.');
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function mobile_register($mobile)
{
$res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['db']->table('users') .
" WHERE mobile_phone = '$mobile'");
return $res;
}

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.

Handling AJAX is not working

I am doing an AJAX call from a function. Everything works fine until the AJAX call(I tried console.log before the AJAX call that was executed). It calls a controller's index function from there it returns the JSON object
in view:
$.ajax({
type: "POST",
url: "<?php echo $this->Html->url('/proposals');?>",
data: form,
dataType: "json",
success: function(data){
//alert(data.id+'--'+data.msg);
console.log("test");
if(data.msg == 'success'){
var valueRemaining= $('#RemainingFunding').val() ;
if (valueRemaining <= 0 ) {
alert ('No Funds Remaining');
return false;
}
var valueSubmitted = $('#subtotal'+state).text();
var valueSubmitted = parseInt(valueSubmitted);
if (valueSubmitted != null || valueSubmitted != '') {
//var substract = valueRemaining - valueSubmitted;
//$('#RemainingFunding').val(substract);
}
//console.log( 'value of subtotao f = ' + subflt );
$('#ProposalId').val(data.id); //ajx_submit
$('#sum').val(data.propsum);
$('#ajx_submit').val(parseInt(tot_ajxsub)+1);
$("input:radio[id=ProposalAnotherLocationY]").prop('checked', false);
$('#fld_subtotal').val('0');
pastSubtotals += flttot;
console.log("test");
tableState=0;
//console.log( 'value of pastSubtotal = ' + pastSubtotals);
//$('#RemainingFunding'). val(intamtval);
}else if(data.msg == 'error'){
alert('Proposal budget can not be blank!!');
return false;
}else {
alert('no match');
}
return false;
//$("#form")[0].reset();
//Unterminated String constant fixed
}
});
Controller:
if ($this - > request - > isAjax()) {
$Proposalsum = $this - > DftsProposalbudget - > find('all', array('fields' => array('SUM(DftsProposalbudget.cy1) as cy1', 'SUM(DftsProposalbudget.cy2) as cy2', 'SUM(DftsProposalbudget.cy3) as cy3 ', 'SUM(DftsProposalbudget.cy4) as cy4 ', 'SUM(DftsProposalbudget.cy5) as cy5', 'SUM(DftsProposalbudget.cy6) as cy6', 'SUM(DftsProposalbudget.cy7) as cy7', 'SUM(DftsProposalbudget.cy8) as cy8', 'SUM(DftsProposalbudget.cy9) as cy9', 'SUM(DftsProposalbudget.cy10) as cy10'), 'conditions' => array('DftsProposalbudget.proposal_id' => $LastID, 'DftsProposalbudget.user_id' => $UID), 'group' => 'DftsProposalbudget.proposal_id'));
$sum = 0;
echo '<pre>'.print_r($Proposalsum, true).
"</pre>";
if (!empty($Proposalsum)) {
foreach($Proposalsum[0][0] as $key => $value) {
//echo $sum += $value['0']['cy1'];
$sum += $value;
}
}
echo json_encode(array('msg' => 'success', 'id' => $LastID, 'propsum' => $sum));
exit(0); //json_encode('msg' => 'success', 'id' => '1');
In the network I get this message:
But it is not printing or working for anything that is in the block success.

FullCalendar recurring events array

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>

Categories