autocomplete jquery codeigniter error - javascript

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.

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

function not defined even though it is

My scripts were working fine yesterday, but today I get an error:
wldk-kurser-admin.js?ver=4.7.5:13 Uncaught ReferenceError: handleSaveAllDokumenterAction is not defined
at HTMLDocument.<anonymous> (wldk-kurser-admin.js?ver=4.7.5:13)
at i (load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,wp-ajax-response,plupload&ver=4.7.5:2)
at Object.fireWith [as resolveWith] (load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,wp-ajax-response,plupload&ver=4.7.5:2)
at Function.ready (load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,wp-ajax-response,plupload&ver=4.7.5:2)
at HTMLDocument.K (load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,wp-ajax-response,plupload&ver=4.7.5:2)
This is my script
(function ($, context) {
$(document).ready(function () {
// makers
listenOnDokumentChangeEvent();
listenOnDokumentToggleEvent();
handleAddDokumentAction();
handleSaveDokumentAction();
handleSaveAllDokumenterAction();
handleRemoveDokumentAction();
// fields
handleMediaUploadField();
});
function listenOnDokumentChangeEvent() {
$('.wldk-kurser-dokument').live('keyup change', function (e) {
// elements
var $wrapper = $(this);
var $dokument = $wrapper.find('input[name=dokument_id]');
var dokumentId = $dokument.val();
var $saveButton = $wrapper.find('.wldk-kurser-save-dokument');
// show that some changes have taken place
if (e.type === 'change') {
$saveButton.addClass('g1gmap-needs-update');
}
// data
var titel = $wrapper.find('[name=dokument_titel]').val();
var fil_url =$wrapper.find('[name=dokument_fil_url]').val();
});
}
function listenOnDokumentToggleEvent () {
$('.wldk-kurser-dokument-toggle').live('click', function (e) {
$(this).parents('li').toggleClass('wldk-kurser-dokument-on wldk-kurser-dokument-off');
});
}
function handleAddDokumentAction() {
$('.wldk-kurser-add-dokument').click(function (event) {
event.preventDefault();
var $wrapper = $(this).parents('#wldk-kurser-new-dokument');
var $kursus = $wrapper.find('input[name=kursus_id]');
var $nonce = $wrapper.find('input[name=update_nonce]');
var $titel = $wrapper.find('input[name=dokument_titel]');
var $fil_url = $wrapper.find('input[name=dokument_fil_url]');
var kursus = $kursus.val();
var titel = $titel.val();
var fil_url = $fil_url.val();
if (!titel || !fil_url ) {
alert(g1_gmap_i18n.required_fields_missing_msg);
return;
}
// ajax call
var xhr = $.ajax({
'type': 'POST',
'url' : ajaxurl,
'data': {
'action' : 'wldk_kurser_add_dokument',
'security' : $nonce.val(),
'ajax_data': {
'kursus_id': kursus,
'titel' : titel,
'fil_url' : fil_url,
}
}
});
// success response
xhr.done(function (response) {
if (response === '0' && response === '-1') {
alert(g1_gmap_i18n.add_marker_error_msg);
return;
}
var $res = $(response);
$res.insertBefore($wrapper);
$wrapper.find('.wldk-kurser-dokument-toggle').trigger('click');
$res.find('.wldk-kurser-dokument-toggle').trigger('click');
handleMediaUploadField();
// clear fields
$titel.val($kursus.val());
$fil_url.val('');
});
});
}
function handleSaveDokumentAction() {
$('.wldk-kurser-save-dokument').live('click', function (event) {
event.preventDefault();
// elements
var $wrapper = $(this).parents('.wldk-kurser-dokument');
var $saveButton = $wrapper.find('.wldk-kurser-save-dokument');
var $nonce = $('#wldk-kurser-new-dokument').find('input[name=update_nonce]');
// data
var dokumentId = $wrapper.find('input[name=dokument_id]').val();
var titel = $wrapper.find('input[name=dokument_titel]').val();
var fil_url = $wrapper.find('input[name=dokument_fil_url]').val();
// validation
if (!titel || !fil_url) {
alert(g1_gmap_i18n.required_fields_missing_msg);
return;
}
// indicate saving action
$saveButton.addClass('g1gmap-marker-saving');
// ajax call
var xhr = $.ajax({
'type': 'POST',
'url' : ajaxurl,
'data': {
'action' : 'wldk_kurser_save_dokument',
'security' : $nonce.val(),
'ajax_data': {
'id' : dokumentId,
'titel' : titel,
'fil_url' : fil_url,
}
}
});
// success response
xhr.done(function (response) {
$wrapper.find('.wldk-kurser-save-dokument')
.removeClass('g1gmap-needs-update')
.removeClass('g1gmap-marker-saving');
if (response === '0' && response === '-1') {
alert(g1_gmap_i18n.save_marker_error_msg);
return;
}
});
});
}
function handleSaveAlldokumenterAction() {
$('.wldk-kurser-save-all-dokumenter').on('click', function (event) {
event.preventDefault();
$('.wldk-kurser-dokument .wldk-kurser-save-dokument').trigger('click');
});
}
function handleRemovedokumentAction() {
$('.wldk-kurser-remove-dokument').live('click', function (event) {
event.preventDefault();
if (!confirm(g1_gmap_i18n.remove_marker_confirm_msg)) {
return;
}
var $wrapper = $(this).parents('.wldk-kurser-dokument');
var $dokument = $wrapper.find('input[name=dokument_id]');
var $nonce = $('#wldk-kurser-new-dokument').find('input[name=update_nonce]');
var dokumentId = $dokument.val();
// ajax call
var xhr = $.ajax({
'type': 'POST',
'url' : ajaxurl,
'data': {
'action' : 'wldk_kurser_remove_dokument',
'security' : $nonce.val(),
'ajax_data': {
'id': dokumentId
}
}
});
// success response
xhr.done(function (response) {
if (response === '0' && response === '-1') {
alert(g1_gmap_i18n.remove_marker_error_msg);
return;
}
// remove edit form
$wrapper.remove();
});
});
}
function handleMediaUploadField() {
$('.g1gmap-media-upload-field:not(.g1-events-bound)').each(function () {
var $field = $(this);
var $clearButton = $('.g1gmap-clear-button', $field);
var $value = $('input.g1gmap-media-upload-input', $field);
var $imagePath = $('.g1gmap-media-upload-image-path', $field);
var $preview = $('.g1gmap-media-upload-preview', $field);
$value.val() ? $clearButton.show() : $clearButton.hide();
$field.addClass('g1gmap-events-bound');
$('.g1gmap-clear-button', $field).click(function () {
$value.val('');
$imagePath.val('');
$clearButton.hide();
$preview.empty();
$(this).trigger('change');
return false;
});
});
$('.g1gmap-media-upload-button').live('click', function () {
var $field_wrapper = $(this).parents('.g1gmap-media-upload-field');
var $input = $field_wrapper.find('.g1gmap-media-upload-input');
var $imagePath = $field_wrapper.find('.g1gmap-media-upload-image-path');
var $preview = $field_wrapper.find('.g1gmap-media-upload-preview');
var $clearButton = $field_wrapper.find('.g1gmap-clear-button');
var frame = wp.media.frames.file_frame = wp.media(
{
title : 'Select media',
button : {
text: 'Save'
},
multiple: false
}
);
frame.on('open', function () {
var id = $input.val();
if (id) {
var selection = frame.state().get('selection');
var attachment = wp.media.attachment(id);
if (attachment) {
attachment.fetch();
}
if (selection) {
selection.add(attachment ? [ attachment ] : []);
}
}
});
frame.on('select', function () {
var attachment = frame.state().get('selection').first().toJSON();
var path = '';
var $img = $('<img>');
if (typeof attachment != 'undefined') {
if (typeof attachment.sizes !== 'undefined' && typeof attachment.sizes.full !== 'undefined') {
$img.attr('src', attachment.sizes.full.url);
path = attachment.sizes.full.url;
} else {
$img.attr('src', attachment.url);
path = attachment.url;
}
}
$input.val(attachment.id);
$imagePath.val(path);
$preview.html($img);
$clearButton.show();
// in some cases, wp media upload doesn't close properly
// so we close it manually
$('.media-modal-close:first').trigger('click');
$field_wrapper.trigger('change');
});
frame.open();
return false;
});
}
})(jQuery, window);
I don't understand it because the function is defined and the handleAddDokumentAction and handleSaveDokumentaction don't cause any problems. I am sure it is something small and trivial, but I just can't see it. I am especially baffled because it seemed to work just fine yesterday.
Relevant PHP:
public function ajax_add_dokument() {
check_ajax_referer( 'wldk-kurser-update-dokumenter', 'security' );
$ajax_data = $_POST['ajax_data'];
$meta_data = array(
'titel' => '',
'fil_url' => '',
);
$meta_data['titel'] = $ajax_data['titel'];
$meta_data['fil_url'] = $ajax_data['fil_url'];
$post_data = array(
'post_status' => 'publish',
'post_type' => 'wldk_kurser_dokument',
'post_title' => $meta_data['titel'],
);
$post_id = wp_insert_post( $post_data );
if ( $post_id === 0 ) {
die();
}
update_post_meta( $post_id, '_wldk_kurser_dokument', $meta_data );
update_post_meta( $post_id, '_wldk_kurser_dokument_titel',
$meta_data['titel'] );
update_post_meta( $post_id, '_wldk_kurser_dokument_fil_url',
$meta_data['fil_url'] );
update_post_meta( $post_id, '_wldk_kurser_dokument_kursus_id',
$ajax_data['kursus_id'] );
echo $this->render_dokument_markup( get_post( $post_id ) );
}
public function ajax_remove_dokument() {
check_ajax_referer( 'wldk-kurser-update-dokumenter', 'security' );
$ajax_data = $_POST['ajax_data'];
$post_id = $ajax_data['id'];
if ( ! $post_id ) {
die();
}
$post = get_post( $post_id );
if ( $post->post_type === 'wldk_kurser_dokument' ) {
// our built-in marker can be removed
$post = wp_delete_post( $post_id, true );
if ( ! $post ) {
die();
}
} else {
// we can't remove post, we can only remove its marker metadata
}
echo 'Dokument successfully removed.';
}
public function ajax_save_dokument() {
check_ajax_referer( 'wldk-kurser-update-dokumenter', 'security' );
$ajax_data = $_POST['ajax_data'];
$post_id = $ajax_data['id'];
unset( $ajax_data['id'] );
if ( ! $post_id ) {
die();
}
$post = get_post( $post_id );
update_post_meta( $post_id, '_wldk_kurser_dokument', $ajax_data );
update_post_meta( $post_id, '_wldk_kurser_dokument_titel',
$ajax_data['titel'] );
update_post_meta( $post_id, '_wldk_kurser_dokument_fil_url',
$ajax_data['fil_url'] );
echo 'Dokument successfully updated.';
}
public function wldk_kurser_dokumenter_meta_box(){
// Add an nonce field so we can check for it later.
wp_nonce_field( 'wldk_kurser_dokumenter_meta_box',
'wldk_kurser_dokumenter_meta_box_nonce' );
/*
// post stored data
$values = get_post_meta( $post->ID, '_g1_gmap', true );
// defined defaults
$defaults = $this->get_map_fields_defaults(
'g1_gmaps_map_markers_meta_box' );
// apply filter on defaults
$defaults = apply_filters( 'g1_gmaps_map_markers_defaults',
$defaults );
// merge values from the database with defaults (on first load in db
there are no values)
$values = wp_parse_args( $values, $defaults );
*/
$args = array(
'meta_key' => '_wldk_kurser_dokument_kursus_id',
'meta_value' => $post->ID,
'post_type' => 'wldk_kurser_dokument',
'orderby' => 'ID',
'order' => 'ASC',
'posts_per_page' => - 1,
);
$dokumenter = get_posts( $args );
// new marker
$ajax_nonce = wp_create_nonce( 'wldk-kurser-update-dokumenter' );
?>
<ul class="wldk-kurser-dokumenter">
<?php foreach ( $dokumenter as $dokument ): ?>
<?php echo $this->render_dokument_markup( $dokument ); ?>
<?php endforeach; ?>
<li class="wldk-kurser-dokumenter-new wldk-kurser-dokument-off"
id="wldk-kurser-new-dokument">
<div class="wldk-kurser-dokument-toggle"><?php echo _e(
'Tilføj nyt dokument', 'g1_gmaps' ); ?></div>
<div class="wldk-kurser-dokument-content">
<table class="form-table">
<tbody>
<tr valign="top">
<th valign="top">
<label>Titel<span class="required">*
</span></label>
</th>
<td>
<input data-g1-label-for="new-marker"
type="text" name="dokument_titel" value="" /><br />
</td>
</tr>
<tr valign="top">
<th scope="row">
<label>Dokument<span class="required">*
</span></label>
</th>
<td>
<input data-g1-label-for="new-marker"
type="text" name="dokument_fil_url" value="" /><br />
</td>
</tr>
</tbody>
</table>
<p class="wldk-kurser-dokument-actions">
<a href="#" class="button button-small wldk-kurser-
add-dokument">Tilføj</a>
<input type="hidden" name="update_nonce" value="<?
php echo esc_attr( $ajax_nonce ); ?>" />
<input type="hidden" name="kursus_id" value="<?php
echo esc_attr( $post->ID ); ?>" />
</p>
</div>
</li>
</ul>
<p class="wldk-kurser-dokumenter-actions">
<a href="#" class="button wldk-kurser-save-all-dokumenter">Gem
alle Dokumenter</a>
</p>
<?php
}
protected function render_dokument_markup( $post ) {
$id = $post->ID;
$values = get_post_meta( $id, '_wldk_kurser_dokument', true );
$marker_type_label = '';
if ( $post->post_type !== 'wldk_kurser_dokument' ) {
$obj = get_post_type_object( $post->post_type );
$marker_type_label = ' (' . $obj->labels->singular_name . ')';
}
?>
<li class="wldk-kurser-dokument wldk-kurser-dokument-off">
<div class="wldk-kurser-dokument-toggle"><?php echo esc_html(
$values['titel'] ); ?></div>
<div class="wldk-kurser-dokument-content">
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">
<label>Titel</label>
</th>
<td>
<input type="text" name="dokument_titel"
value="<?php echo $values['titel']; ?>" /><?php echo esc_html(
$marker_type_label ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row">
<label>Dokument<span class="required">*</span></label>
</th>
<td>
<input data-g1-label-for="new-marker" type="text" name="dokument_fil_url" value="<?php echo $values['fil_url']; ?>" /><br />
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="dokument_id" value="<?php echo esc_attr( $id ); ?>" />
<p class="wldk-kurser-dokument-actions">
Gem
Slet
</p>
</div>
</li>
<?php
}
You have just typo mistake:
Replace block of handleSaveAlldokumenterAction with following:
function handleSaveAllDokumenterAction() {
$('.wldk-kurser-save-all-dokumenter').on('click', function (event) {
event.preventDefault();
$('.wldk-kurser-dokument .wldk-kurser-save-dokument').trigger('click');
});
}
var test=function(){
alert('here');
}
(function ($, context) {
$(document).ready(function () {
test();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your function is not defined when you call it.
Try to define a function with global variable and can call it from any where. Undefined issue will not appeared then

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>

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