function not defined even though it is - javascript

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

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

"missing input response" error recaptcha v3

I'm creating a form to send emails with the recaptcha. Everything was working perfectly, but I noticed that the recaptcha v3 only lasted 3 minutes and needed to reset. From there it started to give a "missing-input-response" error.
index.php
<script>
grecaptcha.ready(function() {
grecaptcha.execute('key', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
});
});
</script>
<script>
var callback = function() {
grecaptcha.render('id-of-render-element', {
'sitekey': 'key',
'expired-callback': expCallback
});
};
var expCallback = function() {
alert("Your recatpcha has expired, please verify again ...");
setInterval(function(){ grecaptcha.reset(); }, 5 * 60 * 1000 );
};
</script>
<div id="id-of-render-element"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=callback&render=explicit" async defer></script>
class captcha
<?php
class Captcha{
public function getCaptcha($SecretKey){
$Resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=key&response={$SecretKey}");
$Retorno = json_decode($Resposta);
return $Retorno;
}
public function returnCaptcha(){
echo "entrou calss_captcha";
$EnviaMail = False;
$ObjCaptcha = new Captcha();
$Retorno=$ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
var_dump($Retorno);
if($Retorno->success == true && $Retorno->score > 0.5){
$EnviaMail = True;
}else{
$EnviaMail = False;
}
return $EnviaMail;
}
}
?>
As per the user comment working for Version 2. You need to specify additional parameters to the file_get_contents function call and If your site has SSL then setting the context options.
class Captcha{
public function getCaptcha($SecretKey){
if($SecretKey){
// Input data
$secret = 'SECRET_KEY';
$response = $SecretKey;
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$post_data = http_build_query(
array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
)
);
$options=array(
// If site has SSL then
'ssl'=>array(
// In my case its /etc/ssl/certs/cacert.pem
'cafile' => '/path/to/cacert.pem',
'verify_peer' => true,
'verify_peer_name' => true,
),
'http' =>array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create( $options );
$Resposta = file_get_contents( $url, false, $context );
$Retorno = json_decode($Resposta);
return $Retorno;
}
}
public function returnCaptcha(){
echo "entrou calss_captcha";
$EnviaMail = False;
$ObjCaptcha = new Captcha();
$Retorno=$ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
var_dump($Retorno);
if($Retorno->success == true && $Retorno->score > 0.5){
$EnviaMail = True;
}else{
$EnviaMail = False;
}
return $EnviaMail;
}
}

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.

JavaScript for two different elements ID working as same function

I'm using this code (http://technologymantrablog.com/dynamic-combobox-ajax-php-mysql/) for getting country/state/city from my database to php/html selects. It's working perfect in registration form. Everything is fine! The problem is, after user register at the system, he can try to edit your registration/profile. Then, the select for country/state/city appears again. And there is the problem. If I use the same ID's from javascript it won't work. If I try to change the ID's and change the javascript, won't work too. Calling two functions and two different files, won't work too.
getSelects.php
function getStatus() {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputStatus").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getStatus.php",true);
xmlhttp3.send();
}
function getMotivo(statusID) {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputMotivo").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getMotivo.php?statusID="+statusID,true);
xmlhttp3.send();
}
function getComplemento(motivoID) {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputComplemento").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getComplemento.php?motivoID="+motivoID,true);
xmlhttp3.send();
}
INCLUDES
Status:
echo '<select onchange="getMotivo(this.value);" class="form-control" name="status" id="status">';
echo
'<option value="">-- Selecione --</option>
<option value="0">Bloqueado</option>
<option value="1">Ativo</option>';
echo'</select>';
Motivo:
include("../lib/conexao.php");
$statusID = $_GET['statusID'];
echo '<select onchange="getComplemento(this.value);" class="form-control" name="motivo" id="motivo">';
echo '<option value="" selected>-- Selecione um Motivo --</option>';
$q = "SELECT * FROM motivo WHERE status = '$statusID' AND tipo = 'C' ORDER BY motivo";
if($res = $con->query($q))
{
while($obj = $res->fetch_object())
{
echo'<option value="'. $obj->motivoID .'">'. $obj->motivo .'</option>';
}
}
echo'</select>';
Complemento:
include("../lib/conexao.php");
$motivoID = $_GET['motivoID'];
if($motivoID == 2 || $motivoID == 4 || $motivoID == 5 || $motivoID == 6 || $motivoID == 8 || $motivoID == 9) {
echo '<label for="complemento">Complemento</label>';
echo '<input type="text" name="complemento" class="form-control" id="complemento" placeholder="Insira o Complemento">';
}
header.php:
<script>
function init() {
getStatus();
}
</script>
</head>
<body onload="init();">
I think if I post all the code files here will be very long post. But, with my text in the first paragraph I think I could explain what I'm trying to do.
I don't know if this will help solve your problem ( hope it does ) but I mentioned using a more or less generic ajax function and using that for the bulk of your work so this is what I meant.
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we have a winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned - a callback is required to handle the response data' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : options;
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState==4 ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method: other methods could be added here */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
/*
example usage:
--------------
*/
function getStatus() {
_ajax.call( this, '/includes/getStatus.php',{ callback:cb_ajax, method:'get', args:{ id:'inputStatus' } } );
}
function getMotivo( statusID ) {
_ajax.call( this, '/includes/getMotivo.php',{ callback:cb_ajax, method:'get', params:{ 'statusID':statusID }, args:{ id:'inputMotivo' } } );
}
function getComplemento( motivoID ) {
_ajax.call( this, '/includes/getMotivo.php',{ callback:cb_ajax, method:'get', params:{ 'motivoID':motivoID }, args:{ id:'inputComplemento' } } );
}
/* The callback function */
function cb_ajax( r, o ){
console.info( 'ajax response: %s, args: %s', r, o );
if( o.hasOwnProperty( 'id' ) && document.getElementById( o.id ) ) document.getElementById( o.id ).innerHTML=r;
}
html form
---------
<form name='so_test_motivo' method='post' action='/test/target.php' enctype="multipart/form-data">
<select name='country' onchange='getStatus()'>
<option value=0 selected> Choose an option
<option value=1> Test
</select>
<select id='inputStatus' name='inputStatus' onchange='getMotivo(this.value)'>
</select>
<select id='inputMotivo' name='inputMotivo' onchange='getComplemento(this.value)'>
</select>
<select id='inputComplemento' name='inputComplemento'>
</select>
</form>
And for the purposes of the test, the php script /test/target.php was simply sending dummy data back like this:
$id=$_GET['id'];
for( $i=0; $i < 50; $i++ ) echo '<option value='.( ( $i+1 ) + $id ).'>Option - '.( ( $i+1 ) + $id ).PHP_EOL;

Storing and returning custom user_meta_data in Wordpress

I'm building a simple Wordpress "Course" website. Each user has to fully watch a video and when the video is complete it opens up the next one.
Currently, I have an update_user_meta tied to my video end() function but after I get that information into the database I'm unsure of how to pull it back out with get_user_meta to treat it almost like a user specific persistent session. Any thoughts from anyone? Or is my approach wrong?
This is what I have so far based off of this: https://patrickshampine.com/2014/updating-user-meta-admin-ajax-frontend/
html:
<dl class="accordion">
<dt><a class="checkbox" id="video-1" href="">Instructions</a></dt>
<dd class="video" id="dd-1">
<p id="video-message"></p>
<p id="wistia_id" class="wistia_embed" style="width:640px;height:360px;"></p>
</dd>
<div class="inactive" id="video-2fake"><a>History</a></div>
<dt><a id="video-2" class="hidden" href="">History</a></dt>
<dd class="video" id="dd-2">
<p id="video-message"></p>
<p id="wistia_id" class="wistia_embed" style="width:640px;height:360px;"></p>
</dd>
</dl>
In the theme functions.php:
add_action( 'wp_ajax_video_end', 'updateVideo' );
function video_scripts() {
$parameters = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('video')
);
wp_enqueue_script('video-ajax', get_template_directory_uri().'/js/ajax.js', array('jquery'), null, true);
wp_localize_script('video-ajax', 'video', $parameters );
}
add_action('wp_enqueue_scripts', 'video_scripts');
function ajaxStatus($status, $message, $data = NULL) {
$response = array (
'status' => $status,
'message' => $message,
'data' => $data
);
$output = json_encode($response);
exit($output);
}
function updateVideo() {
if(empty($_POST) || !isset($_POST)) {
ajaxStatus('error', 'Nothing to update.');
} else {
$data = $_POST;
$dataString = $data['post'];
parse_str($dataString, $dataArray);
$nonce = $data['nonce'];
if(wp_verify_nonce($nonce, 'video') !== false) {
$user_ID = get_current_user_id();
$dataArray['watched'] = isset($dataArray['watched']) ? true : false;
if($user_ID != NULL) {
foreach($dataArray as $key=>$value) {
$status = update_user_meta($user_ID, $key, $value);
}
ajaxStatus('success', 'updated', $dataArray);
} else {
ajaxStatus('error', 'You are unauthorized to perform this action.', $dataArray);
}
} else {
ajaxStatus('error', 'Nonce check cannot fail.');
}
}
}
Then the javascript:
video1 = Wistia.embed("");
video2 = Wistia.embed("");
jQuery(document).ready(function($) {
var response;
var allPanels = $('.accordion > dd').hide();
$('.accordion > dt > a').click(function() {
allPanels.slideUp();
$(this).parent().next().slideDown();
if(this)
return false;
});
var watched = '<span>☑</span>',
visible1 = false,
visible2 = false,
$("#dd-1").show();
video1.bind("end", function () {
$( "#video-2").removeClass("hidden");
$( "#video-2fake").hide();
allPanels.slideUp();
$("#dd-2").slideDown();
if(!visible1) {
$( "#video-1" ).append( watched );
visible1 = true;
}
else {
if(visible1) {
$( "#video-1" ).remove( watched );
visible1 = false;
}
}
$.post( video.ajaxurl, {
action : 'video_end',
nonce : video.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
responseSuccess(response);
});
return false;
function responseSuccess(data) {
response = JSON.parse(data);
if(response.status === 'success') {
$('#video-message').text(response.message);
} else {
$('#video-message').text(response.message);
}
}
});
video2.bind("end", function () {
$( "#video-3").removeClass("hidden");
$( "#video-3fake").hide();
allPanels.slideUp();
$("#dd-3").slideDown();
position = "2";
alert(position);
if(!visible2) {
$( "#video-2" ).append( watched );
visible2 = true;
}
else {
if(visible2) {
$( "#video-2" ).remove( watched );
visible2 = false;
}
}
$.post( video.ajaxurl, {
action : 'video_end',
nonce : video.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
responseSuccess(response);
});
return false;
function responseSuccess(data) {
response = JSON.parse(data);
if(response.status === 'success') {
$('#video-message').text(response.message);
} else {
$('#video-message').text(response.message);
}
}
});
});

Categories