Loading Gravity Form via Ajax results in - php

I am trying to load a gravity form via Ajax. I have the form loading during a user action from another javascript. The form loads and submits perfectly as long as there is a date field on the form. As soon as I remove the date field from the form, I get this error:
Uncaught ReferenceError: gformInitSpinner is not defined
I have tried the solutions suggested in js error on gravity forms but was not able to solve the problem.
<?php
function plc_ajax_get_form(){
$available_forms = [
'Create Opponent',
'Simple'
];
# To Do:
# make sure that the user has permission
if (isset ($_POST['form']) && in_array ($_POST['form'], $available_forms)) {
$f = PLCForms::get($_POST['form']); // <- Custom method just to get the form id by name.
# gravity_form_enqueue_scripts ($f->id, true); // This method doesn't work
gravity_form ($f->id, true, false, false, false, true);
}
else {
print 'No form found.';
}
die;
}
add_action ('wp_ajax_plc_get_form', 'plc_ajax_get_form');
Ajax Script
(function ($) {
window.testCall = function (form, name, val) {
var data = {
action: 'plc_get_form',
security : PLCGetForm.security,
form: form
};
$.post (PLCGetForm.ajaxurl, data, function (response) {
$('body').append('<div class="lb-form" style="background: white;width: 100%;position: absolute;top: 50px;z-index:1000;">' + response + '</div>');
$('.lb-form form input[name="' + name + '"]').val(val);
processLBForm (form, testCallback);
});
};
window.testCallback = function (data) {
console.log (data);
};
window.processLBForm = function (form, callback) {
$('.lb-form form').submit(function (e){
e.preventDefault();
var data = {
action: 'plc_gf_submit',
security: PLCGFSumbit.security,
form: form,
data: $(this).serializeArray()
};
$.post (PLCGFSumbit.ajaxurl, data, function (response) {
data = JSON.parse(response);
$('.gform_ajax_spinner').remove();
if (data.is_valid) {
$('.lb-form form .gform_heading, .lb-form form .gform_body, .lb-form form .gform_footer, .lb-form form .validation_error').remove();
var m = '';
if (typeof (data.confirmation_message) == 'string') {
m = data.confirmation_message;
}
else {
m = 'Your data was saved.';
}
m = '<div id="gform_confirmation_wrapper_2" class="gform_confirmation_wrapper "><div id="gform_confirmation_message_2" class="gform_confirmation_message_2 gform_confirmation_message">' + m + '</div></div>';
$('.lb-form form').append (m);
if (typeof (callback) === 'function') {
callback (data);
}
}
else if (typeof(data.validation_messages) == 'object') {
var m = '';
$('.lb-form form .validation_error').remove();
$('.lb-form form .validation_message').remove();
for (var key in data.validation_messages) {
// Skip loop if the property is from prototype
if (!data.validation_messages.hasOwnProperty(key)) continue;
$('.lb-form form input[name="input_' + key + '"]').parents('.gfield').addClass('gfield_error');
$('.lb-form form input[name="input_' + key + '"]').parents('.gfield').append('<div class="gfield_description validation_message">' + data.validation_messages[key] + '</div>');
}
$('.lb-form form .gform_heading').after ('<div class="validation_error">There was a problem with your submission. Errors have been highlighted below.</div>');
$('.lb-form form input[type="submit"]').click(function(){
$('.lb-form form').submit();
});
}
else {
$('.lb-form form .validation_error').remove();
$('.lb-form form .gform_heading').after ('<div class="validation_error">There was a problem with your submission. No validation messages were set. Please contact your admin.</div>');
$('.lb-form form input[type="submit"]').click(function(){
$('.lb-form form').submit();
});
}
});
});
};
})(jQuery);
Init Script
(function ($) {
$(document).ready(function(){
testCall('Simple', 'input_1', 'test');
});
})(jQuery);
Does anyone know what the date field is doing differently to the scripts to make them work? Any help is greatly appreciated, thanks.
Update
The form with the date field is another form on the page... I just realized it was not the one being called via ajax... So I need to find the difference in the page that is already being loaded via a shortcode, which seems to make the ajax form work. Adding the ajax to the shortcode doesn't work.
[gravityform id="2" title="true" ajax="true"]
Will update if I find the script. Thanks.

The gravity forms js was not loading as I suspected, but was calling gravity_form_enqueue_scripts ($f->id, true); from the wrong location. It needs to be called from the page that the form is loaded into and not on the ajax'ed form itself.
function plc_enqueue_scripts_styles ($hook) {
gravity_form_enqueue_scripts (16, true); // Ajaxed form id = 16
}
add_action ('wp_enqueue_scripts', 'plc_enqueue_scripts_styles');

Related

check email availability in Codeigniter without going to database and disable form to submitting till email is available

I am using Codeigniter and i am creating a login registration form which check the email of user that it available or not. User can login with that id.
So I am Trying to use Ajax for it.
So I have Put this Ajax in my View.
$(document).ready(function() {
$("#email").keyup(function() {
var email = $(this).val();
if (email.length > 3) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: emailAvailability,
data: { email: email },
success: function(data) {
console.log(data);
$("#result").html(data);
if (data.indexOf('Available')) {
emailAvaliable = 1;
//$('#candidateLogin').removeClass('disabled');
} else {
emailAvaliable = 0;
//$('#candidateLogin').addClass('disabled');
}
}
});
return false;
} else {
$("#result").html('');
}
});
});
I am Using parsley plugin for validation.
$(".formValidationClass").on('click', function (e) {
e.preventDefault;
$(this).parsley();
});
Now the Controller Code.
public function check_email_availability(){
$data = $this->input->post();
// Now I want to check email is unique or not without going to database.
}
The Second Problem is i want to disable the form till email is available & valid.
I have tried this script to disable the form to submit but it's not working and form get submitted. I have done the server side validation to not submit but still i want to prevent it form the client side.
this is the script.
$(".formValidationClass").on('click', function(e) {
e.preventDefault;
$(this).parsley().validate();
console.log('on form click, After validation');
// return false;
});
var emailAvaliable = 0;
$(".formValidationClass").submit(function(event) {
// Validate form fields
if (emailAvaliable == 1) {
console.log('Email Avaliable');
$(this).parsley();
return true;
} else {
console.log('Email not Avaliable');
return false;
}
});
All the suggestion related improving the code is acceptable. Thanks.
if you want to prevent the form submit event then please use: e.PreventDefault(); Check this Using JQuery - preventing form from submitting for more information. I think this is useful for you.

jQuery load() not functioning as expected

I've a jquery script that call the number2.php page, which is supposed to execute and show the result in a <div>. The problem is that is not working. Can you help me? Thanks.
<script>
$(function() {
$('#submit').click(function() {
if ($('#taille').val() != 0) {
var param = 'l=' + $('#taille').val();
}
else {
var param = 'b=' + $('#datepicker').val() + 'c=' + $('#datepicker1').val() + 'num' + $('#num').val();
}
$('#retour').load('number2.php', param);
);
});
</script>
Your code has a syntax error; it's missing closing } in the click handler function.
now it works but after loading number2.php my main page is refreshed and i lose the result !!!
In this case, you should hook to the submit event of the form element and call preventDefault() on the event to prevent the normal form submission. Try this:
$(function() {
$('#myForm').submit(function(e) { // change #myForm to target the <form>
e.preventDefault();
var param = {};
if ($('#taille').val() != 0) {
param.l = $('#taille').val()
}
else {
param.b = $('#datepicker').val();
param.c = $('#datepicker1').val();
param.num = $('#num').val();
}
$('#retour').load('number2.php', param);
});
});

Saving form state with javascript only on submit

So. I have a Form with a lot of checkboxes. Along with that I have a piece of javascript code that is supposed to save the state of every checkbox when the user presses submit. My short and irritating problem is two things.
Question: I want to save Checkbox state to cookie ONLY when I submit the form, right now it saves if I mark a checkbox and reload the page, without submitting. Im working with Javascript and Cookies, two things that Im quite new to. So Im very greatful for all help. Here is my code that I got from here:
function getStorage(key_prefix) {
if (window.localStorage) {
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = unescape(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val == 'checked') $(this).attr('disabled','true');
if (val) $(this).trigger('change');
});
});
So I want to save to cookie only on submit basically.
Bind to the submit event of the form instead of the change event of all the checkboxes.
Try this in place of your second function:
jQuery(function($) {
// bind to the submit event of the form
$('#id-of-your-form').submit(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// save checkbox states to cookie
$('div.check input:checkbox').each(function() {
// for each checkbox, save the state in storage with this.id as the key
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
});
});
});
jQuery(document).ready(function() {
// on load, restore the checked checkboxes
$('div.check input:checkbox').each(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// for each checkbox, load the state and check it if state is "checked"
var state = storedData.get(this.id);
if (state == 'checked') {
$(this).attr('checked', 'checked');
}
});
});

multiple form actions, return any validation errors and refresh results on successful submission

I have a table filled from the database. Each row has a checkbox. When you select (multiple) checkboxes i want to be able to press:
one button to change $row->status for all checked rows
another button to convert each checked row's contents into form elements.(i've been doing this by choosing different templates in the view depending on if isset($_POST['ap']))
then i will need a submit button to save any changes to these rows.
I am using codeigniter and have been using jquery.form to submit forms.
My main problem is combining the two functions below and making the code as reusable as possible (i have a few similar pages for different data). $('.form_js') feeds back validation_errors(); but it doesn't allow for different table actions.
Thanks in advance
Here's my current code:
$('.form_js').submit(function(){
var options = { target: $(this).find(".error")};
$(this).ajaxSubmit(options);
return false;
});
function form_action(controller){
var original_url = window.location;
var form = $("#ap_table");
var list = $(':checkbox[name="ap[]"]:checked').map(function(){
return $(this).val();
}).get().join(',');
alert(base_url + controller + "?ap=" + list);
form.attr('action', base_url + controller + "?ap_id=" + list);
return false;
}
I managed to do this with a fresh mind and this code.
$('input[type=submit]').click(function()
{
var form = $("#numbers");
var submit_button = $(this).attr('value');
if(submit_button == 'Cancel' || submit_button == 'Pause')
{
var controller = 'numbers/status_msg/' + submit_button;
var list = $(':checkbox[name="phone_id[]"]:checked').map(function(){
return $(this).val();
}).get().join(',');
form.attr('action', base_url + controller + '?ids=' + list);
}
/*if($(this).attr('value') == 'Multi Edit')
{
//allow form to submit to default action '#'
}*/
if($(this).attr('value') == 'Save All')
{
var controller = 'numbers/multi_update/';
var options = { target: $(form).find(".error")};
form.attr('action', base_url + controller );
alert(form.attr('action'));
$(form).ajaxSubmit(options);
return false;
}
});
then in 'numbers/multi_update' load view on successful submission with:
if($("input[name=redirect]").val())
{
//Add $insert_id to the redirect url
var redirect_url = $("input[name=redirect]").val() + "/<?php echo $insert_id; ?>";
//redirect
window.location = base_url + redirect_url;
}
This works but is there an easier way?

php mysql not saving data when button clicked and run $.ajax function

I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect

Categories