Adding non-required fields to form - php

I am trying to add non-required fields but not sure how to add multiple strings. Adding one is fine but it stops working when I add multiple. Can anyone point out what I may be missing? Below is the code;
jQuery( '#appointment-popup' ).on( 'click', 'input.submit-appointment', function() {
values = {
'name' : '',
'phone' : '',
'email' : '',
'appointment-date' : '',
'approximate-time' : '',
'place' : '',
'additional-notes' : '',
'solutions' : ''
};
areErrors = false;
jQuery.each( values, function( key, value ) {
currentElement = jQuery( '#appointment-form-in-popup form *[name='+ key +']' );
values[key] = currentElement.val();
if( key != 'additional-notes' ) { // put here unrequired fields
if( values[key] != false ) { currentElement.removeClass( 'error' ); }
else {
currentElement.addClass( 'error' );
areErrors = true;
}
}
});
if( areErrors == false ) {
// your action here, for example sending an email...
jQuery.ajax({
url: path_to_template +'/_assets/submit.php',
data: { 'submit': 'appointment-form', 'data': values, 'email': appointment_contact },
type: 'post',
success: function( output ) {
// animation after your action
jQuery.appointmentFormAnimation();
}
});
}
});
jQuery.appointmentFormAnimation = function() {
formHeight = jQuery( '.appointment-popup-content' ).height();
jQuery( '.appointment-popup-content' ).css({ 'minHeight' : formHeight });
jQuery( '#appointment-form-in-popup form' ).fadeOut( 300 );
setTimeout( function() {
jQuery( '#appointment-form-in-popup .thanks' ).fadeIn( 300 );
}, 400 );
}

Related

Wordpress Ajax - Js error 400(bad request)

It's getting the link to the word press ajax file but giving me a bad request error.
The exact error im getting is POST http://[Website URL]/wp-admin/admin-ajax.php 400 (Bad Request)
Functions.php file
function as_custom_ajax_localizing() {
wp_enqueue_script( 'custom.js', get_template_directory_uri() . '/guest-list/custom.js', array( 'jquery' ), '1.0.0', true );
wp_localize_script( 'custom.js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'as_custom_ajax_localizing' );
Custom php file
add_action( 'wp_ajax_my_delete_post', 'as_delete_guest' );
function as_delete_guest(){
$permission = check_ajax_referer( 'as_delete_guest_nonce', 'nonce', false );
if( $permission == false ) {
echo 'error';
} else {
wp_delete_post( $_REQUEST['id'] );
echo 'success';
}
die();
}
Custom Js file
$( document ).ready(function() {
$( ".remove_guest" ).click(function() {
var guestRowId = $(this).attr('id');
alert( "This id is " + guestRowId + " and has been clicked");
var nonce = $(this).data('nonce');
$.ajax({
type: 'post',
url: MyAjax.ajaxurl,
data: {
action: 'my_delete_post',
nonce: nonce,
id: guestRowId
},
success: function( result ) {
if( result == 'success' ) {
alert("Success");
}
else{
alert("problem");
}
}
})
return false;
});
});

Called and canceled of the admin-ajax.php file multiple times

I have an issue in a Wordpress installation with a plugin. There is a calendar which you can click on a day (or a range of days) and from ajax calls through admin-ajax.php it calculates product costs.
The problem is that, when I click on a calendar cell, the admin-ajax.php is called twice. The first time for a few milliseconds and canceled immediately. Then automatically, it calls it once again and get the ajax response. When I click for a second time on a calendar cell, the admin-ajax.php is called 3 times. The first two are canceled and only the last one get a response.
I found that the code that is used for this part is the following. However, I cannot find any issue on it, even if I can see those cancelled calls on Developer console.
$('.wc-bookings-booking-form')
.on('change', 'input, select', function() {
var index = $('.wc-bookings-booking-form').index(this);
if ( xhr[index] ) {
xhr[index].abort();
}
$form = $(this).closest('form');
var required_fields = $form.find('input.required_for_calculation');
var filled = true;
$.each( required_fields, function( index, field ) {
var value = $(field).val();
if ( ! value ) {
filled = false;
}
});
if ( ! filled ) {
$form.find('.wc-bookings-booking-cost').hide();
return;
}
$form.find('.wc-bookings-booking-cost').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
xhr[index] = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_calculate_costs',
form: $form.serialize()
},
success: function( code ) {
if ( code.charAt(0) !== '{' ) {
console.log( code );
code = '{' + code.split(/\{(.+)?/)[1];
}
result = $.parseJSON( code );
if ( result.result == 'ERROR' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').addClass('disabled');
} else if ( result.result == 'SUCCESS' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').removeClass('disabled');
} else {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
console.log( code );
}
},
error: function() {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
},
dataType: "html"
});
})
.each(function(){
var button = $(this).closest('form').find('.single_add_to_cart_button');
button.addClass('disabled');
});
And here is a screenshot from the Dev Console:
EDIT: I think I found the problem, but I am not sure. There is also this part of code which was supposed to not used at all. There is a feature for time on calendar, but it isn't activated. So, this code should not be run.
$('.wc-bookings-booking-form').on( 'date-selected', function() {
show_available_time_blocks( this );
});
var xhr;
function show_available_time_blocks( element ) {
var $form = $(element).closest('form');
var block_picker = $form.find('.block-picker');
var fieldset = $form.find('.wc_bookings_field_start_date');
var year = parseInt( fieldset.find( 'input.booking_date_year' ).val(), 10 );
var month = parseInt( fieldset.find( 'input.booking_date_month' ).val(), 10 );
var day = parseInt( fieldset.find( 'input.booking_date_day' ).val(), 10 );
if ( ! year || ! month || ! day ) {
return;
}
// clear blocks
block_picker.closest('div').find('input').val( '' ).change();
block_picker.closest('div').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
// Get blocks via ajax
if ( xhr ) xhr.abort();
xhr = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_get_blocks',
form: $form.serialize()
},
success: function( code ) {
block_picker.html( code );
resize_blocks();
block_picker.closest('div').unblock();
},
dataType: "html"
});
}

Form validation using jquery, php and sql

I am trying to validate part of a form, I am stuck on checking the database to see if a company name exists before submitting the form. This is a stripped down demo from the jquery ui modal from with the addition of checking if the company already exists. I am aware of SQL injection and am not doing anything about it just yet. At the moment the form won't submit as I'm missing something, I just don't know what yet.
Any help would be much appreciated.
This is what I have so far
The JS code:
$(function() {
var dialog, form,
company_name = $( "#company_name" ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkCompany( o, n ) {
$.ajax({
type: "POST",
url: "crud.php?act=check",
data: "&company_name=" + o.val(),
success: function(response){
if(response > 0){
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
})
}
function addUser() {
var valid = true;
valid = valid && checkCompany( company_name, "Company Name already exists." );
if ( valid ) {
$.ajax({
type: "POST",
url: "crud.php?act=create",
data: "&company_name=" + company_name.val(),
success: function(data){
}
});
dialog.dialog( "close" );
}
return valid;
}
dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 350,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser();
});
$( "#create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
});
The php side (crud.php):
include 'connection.php';
$action = $_GET['act'];
if(isset($_POST['company_name'])){
$company_name = $_POST['company_name'];
}
switch($action){
case 'create':
$q = "INSERT INTO company_info (company_name) VALUES
('".$company_name."')";
mysql_query($q);
break;
case 'check':
$result = mysql_query('SELECT company_name FROM company_info WHERE company_name = "'.$company_name.'"');
$num = mysql_num_rows($result);
echo $num;
break;
}
CheckCompany returns nothing. You are returning true or false from success but that goes nowhere.
You need an outer deferred so you can return something from your ajax success, back through checkcompany out to your call.
Basically, checkcompany is called and exits/returns normally. SOme time later, the success function runs but that is independent because it's async. It's not part of your checkcompanmy function.
Ideally, you should trigger an event on ajax success that your element subscribes to.
Examples from comment below:
checkCompany(o,n) {
var retval = false;
$.ajax({
sync : true,
success: function(data) {
retval = true;
}
});
return retval;
}
OR asynch:
checkCompany(o,n) {
$.ajax({
success: function(data) {
$("#ID").trigger('ajsuccess.company');
}
});
}
OR using returned promise:
if (valid) {
checkCompany().done(function() {
do the secondary ajax call in here
}
}
checkCompany(o,n) {
return $.ajax();
}

Dynamically checking and unchecking a task tree

I'm having issues making a task tree I have dynamically check boxes. Basically if a top level (parent task) is checked, I would like it to check all of the subtasks (child boxes). I have this working on one of my task trees, but for some reason can't get it to work for my other.
<script>
$(function() {
$.ajaxSetup( { cache: false } );
$('.task-tree').tree({
ui: {
theme_name: 'checkbox'
},
plugins : {
checkbox: { three_state: false }
},
callback: {
onload: function( tree ) {
tree.open_all();
$('.task-tree li a').each( function() {
var taskID = GetIdNum( $(this).attr('id') );
if ( $('#Task' + taskID + 'Enabled').val() == 1 )
{
console.log( $(this).parent() );
jQuery.tree.plugins.checkbox.check( $(this).parent() );
}
});
},
onchange: function( node, tree ) {
var selectedID = GetIdNum( $(node).find('a').attr('id') );
var required = $('#Task' + selectedID + 'Required').val();
console.log( 'REQ --> ' + required );
if ( required == 1 )
{
return false;
}
else
{
$('.task-tree li a').each( function() {
var taskID = GetIdNum( $(this).attr('id') );
console.log( taskID );
$('#Task' + taskID + 'Enabled').val(1);
});
console.log( '----------------------------------------------' );
var unchecked = jQuery.tree.plugins.checkbox.get_unchecked(tree).find('a.not-required');
$(unchecked).each( function(){
var taskID = GetIdNum( $(this).attr('id') );
console.log( taskID );
$('#Task' + taskID + 'Enabled').val(0);
});
console.log( '*************************************************' );
}
}
}
});
});
Let me know if you need any more info about the problem.

accessing the jquery function after success call?

jQuery(function ($) {
/* fetch elements and stop form event */
$("form.follow-form").submit(function (e) {
/* stop event */
e.preventDefault();
/* "on request" */
$(this).find('i').addClass('active');
/* send ajax request */
$.post('listen.php', {
followID: $(this).find('input').val()
}, function () {
/* find and hide button, create element */
$(e.currentTarget)
.find('button').hide()
.after('<span class="following"><span></span>Following!</span>');
});
});
});
i want to know what when i process the mysql query in the listen.php file, how deos it get the success message back, and then perform the change after?
UPDATE
PHP code:
<?php
if ( $_POST['action'] == 'follow' ) {
$json = '';
if ( $_POST['fid'] == "2" ) {
$json = array( array( "id" => 1 , "name" => "luca" ),
array( "id" => 2 , "name" => "marco" )
);
}
echo json_encode($json);
}
?>
jQuery code:
$.ajax({
type: 'POST',
url: 'listen.php',
data: 'action=follow&fid=' + 2, //$(this).find('input').val(),
success: function(data) {
var obj = $.parseJSON(data);
for ( var i = 0; i < obj.length; i++ ) {
alert( obj[i].id + ' ' + obj[i].name )
}
},
complete: function(data) {
//alert(data.responseText);
},
error: function(data) {
alert(data);
}
});
it's XMLHTTP Object that is responsible behind the scene.
your php script should output text... so lets say the query works output "YES" if it doesn't output "NO" then use this function in your $.post():
function (data) {
if(data=="YES"){
// worked
}
else{
// didn't work
}
}

Categories