I am trying to make AJAX form validation work in CodeIgniter.
If you have the same title don't add The data from the form always reports as successful, even if the result is negative.
Is there a mistake in my logic?
Save controller:
public function save(){
$options = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$data['options'] = json_encode($options);
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$validate = $this->form_validation->run();
if($validate){
$insert = $this->db->insert('product', $data);
// alert
if($insert){
$alert = array(
"title" => "Success Sir",
"text" => "Content successfully added",
"type" => "success"
);
}else {
$alert = array(
"title" => "Error Sir",
"text" => "Content failed to load content,
"type" => "danger"
);
}
}
JSON, AJAX, jQuery:
function ajax_set_full(type, title, noty, form_id, id) {
// ajax func
ajax_load(base_url + '' + user_type + '/' + module + '/' + type + '/' + id, 'list', 'form');
}
function form_submit(form_id, noty, e) {
var alerta = $('#form'); // alert div for show alert message
var form = $('#' + form_id);
var can = '';
if (!extra) {
var extra = '';
}
form.find('.summernotes').each(function () {
var now = $(this);
now.closest('div').find('.val').val(now.summernote('code'));
});
//var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var a = 0;
var take = '';
form.find(".required").each(function () {
var txt = '*' + req;
a++;
if (a == 1) {
take = 'scroll';
}
var here = $(this);
if (here.val() == '') {
if (!here.is('select')) {
here.css({borderColor: 'red'});
if (here.attr('type') == 'number') {
txt = '*' + mbn;
}
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' ' + txt
+ ' </span>'
);
}
} else if (here.is('select')) {
here.closest('div').find('.chosen-single').css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' *Required'
+ ' </span>'
);
}
}
var topp = 100;
if (form_id == 'product_add' || form_id == 'product_edit') {
} else {
$('html, body').animate({
scrollTop: $("#scroll").offset().top - topp
}, 500);
}
can = 'no';
}
if (here.attr('type') == 'email') {
if (!isValidEmailAddress(here.val())) {
here.css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="require_alert" >'
+ ' *' + mbe
+ ' </span>'
);
}
can = 'no';
}
}
take = '';
});
if (can !== 'no') {
if (form_id !== 'vendor_pay') {
$.ajax({
url: form.attr('action'), // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formdata ? formdata : form.serialize(), // serialize form data
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formdata);
var buttonp = $('.enterer');
buttonp.addClass('disabled');
buttonp.html(working);
},
success: function () {
ajax_load(base_url + '' + user_type + '/' + module + '/' + list_cont_func + '/' + extra, 'list', 'first');
if (form_id == 'vendor_approval') {
noty = enb_ven;
}
iziToast.show({
color: 'dark',
icon: 'fa fa-info',
title: 'Bilgi',
message: 'İşlem Başarılı!',
position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
/*onOpening: function(){
setTimeout(function(){
window.location.reload(1);
}, 5000);
console.log('Page Refresh!');
},
onClosing: function(){
// console.log('goodbye');
}*/
});
$('.bootbox-close-button').click();
('form_submit_success');
other_forms();
},
error: function (e) {
console.log(e)
}
});
} else {
//form.html('fff');
form.submit();
//alert('ff');
return false;
}
} else {
if (form_id == 'product_add' || form_id == 'product_edit') {
var ih = $('.require_alert').last().closest('.tab-pane').attr('aria-labelledby');
$("[id=" + ih +"]").click();
}
$('body').scrollTo('#scroll');
return false;
}
}
The error message always returns positive.
after run the validation, you need specify the array to be validated
public function save(){
$data = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$this->form_validation->set_data($data);
$validate = $this->form_validation->run();
You have to call the set_data() method before defining any validation rules.
Ref: https://codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post
Related
I have a form that utilizes jqGrid to display personalized info for the user to select from. Everything works fine however on the "Review" page there is an option to edit the form. When you click edit and go back into the form selections all values selected are retained except for the jqGrid portion of the form that uses the checkbox values. How can I have this value retained so the user doesn't have to make the selection again?
var myGrid;
var blnListsFound = true;
var blnGridLoading = false;
function fnInitialize() {
// Initialize the screen
fnLoadForm();
$('#no_transactions').hide();
// alert("fnInitialize(): JS loaded fine, no errors");
}
function fnACHSwapGetGrid() {
blnListsFound = true;
// make sure we have a from account
if ($('#selFromAccount').val() == '0') {
return;
}
$('#imgWaitselFromAccount').show(); // show loading icon
var urlString = '';
var urlParams = new Array();
// urlParams['rc'] = escape($('#RC').val());
urlParams['RC'] = escape($('#txtMenuRC').val());
urlParams['acctNBR'] = escape($('#selFromAccount').val());
// get application type from aryAccount
for (act in aryAccount) {
if (aryAccount[act]['Number'] == urlParams['acctNBR']) {
urlParams['Appl'] = aryAccount[act]['Application'];
break;
}
}
$.jgrid.gridUnload("#list");
myGrid = $("#list").jqGrid({
url: baseURL + '/scripts/get_user_list.php' + urlString,
datatype: "json",
mtype: 'POST',
width: 660,
height: '100%',
pager: '#pager',
rowNum: 10,
rowList: [20, 30, 40, 50, 60],
sortname: 'id',
sortorder: "asc",
viewrecords: true,
multiselect: true,
repeatitems: false,
imgpath: '/scripts/jquery-ui/images',
colNames: ['id', 'Building', 'Company ID', 'Description', 'Individual Name', 'SECCode'],
colModel: [
{name: 'id', index: 'id', jsonmap: 'id', hidden: true, width: 20},
{name: 'Building', index: 'Building', jsonmap: 'Building', hidden: true, width: 20},
{name: 'CompanyId', index: 'CompanyId', jsonmap: 'CompanyId', width: 110},
{name: 'Description', index: 'Description', jsonmap: 'Description', sortable: true, width: 300},
{name: 'IndName', index: 'IndName', jsonmap: 'IndName', width: 200},
{name: 'UsrNum', hidden: true, index: 'UsrNum', jsonmap: 'UsrNum'}
],
jsonReader:
{
repeatitems: false,
root: 'rows',
id: '0',
cell: '',
subgrid:
{
root: 'rows',
id: '0',
cell: '',
repeatitems: false
}
},
// subgrid support
subGrid: true,
subGridUrl: baseURL + '/scripts/get_user_list.php' + urlString,
subGridModel: [{
name: ['Date', 'ID'],
params: ['CompanyId'],
align: ['center', 'right'],
width: [150, 80]}
],
ondblClickRow: function (id)
{
$('#recId').val(id);
},
beforeRequest: function ()
{
blnGridLoading = true;
// console.log("beforeRequest(); setting blnGridLoading=true");
fnValidateAccount(); // Check that user has data available
},
loadComplete: function ()
{
blnGridLoading = false;
// console.log("loadcomplete(); setting blnGridLoading=false");
for (swap in arySwap)
{
if (typeof arySwap[swap]['CompanyId'] != 'undefined')
{
$("#list").jqGrid('setSelection', arySwap[swap]['CompanyId']); // select companyId
}
}
fnValidateAccount(); // Check that user has data available
},
loadError: function (jqXHR, textStatus, errorThrown)
{
blnGridLoading = false;
blnListsFound = false; // no data found for this account
// console.log("loadError() setting blnGridLoading=false and blnListsFound=false");
fnValidateAccount(); // Check that user has data available
//alert('HTTP status code: ' + jqXHR.status + '\n' +
// 'textStatus: ' + textStatus + '\n\n ' +
// 'errorThrown: ' + errorThrown);
//alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
})
.navGrid('#pager', {edit: false, add: false, del: false, search: false, refresh: true});
//$("#list").closest('.ui-jqgrid-bdiv').width($("#list").closest('.ui-jqgrid-bdiv').width() + 10);
$('#imgWaitselFromAccount').hide(); // hide loading icon
fnfldDisable("selToAccount", false);
}
function fnLoadForm() {
for (swap in arySwap) {
if ($('#selFromAccount').val() != 0) {
break; // populate just once
}
if (typeof arySwap[swap]['FromAccount'] != 'undefined' // have swap data
&& arySwap[swap]['FromAccount'] != '' // and its not blank
)
{
$('#selFromAccount').val(arySwap[swap]['FromAccount']);
$('#selFromAccount').change(); // trigger change calls
$('#selToAccount').val(arySwap[swap]['ToAccount']);
$('#selToAccount').change(); // trigger change calls
}
}
}
function fnGetAccountTitle(objAccount, fldTitle) {
if (typeof objAccount != 'object') {
return false;
}
if (typeof fldTitle != 'string') {
return false;
}
if ($('#' + fldTitle).length) {
$('#' + fldTitle).val('');
var curAccount = fnGetSelected(objAccount);
for (act in aryAccount) {
if (aryAccount[act]['Number'] == curAccount) {
var Application = fldTitle.replace('Title', 'Application');
$('#' + fldTitle).val(aryAccount[act]['Title']);
$('#' + Application).val(aryAccount[act]['Application']);
return;
}
}
}
}
function fnValidateAccount() {
var blndoSubmit = true;
// console.log("fnValidateAccount() called.");
$("#list").removeClass("errmark"); // reset error display
if (blnGridLoading) {
$("#no_data").hide();
reValidateTimer = setTimeout("fnValidateAccount()", 2000);
// console.log("Grid loading, retrying validation in 5 seconds");
blndoSubmit = false;
}
else {
var numRows = $("#list").jqGrid('getGridParam', 'records'); // rows available
var selRows = $("#list").jqGrid('getGridParam', 'selarrrow'); // rows selected
if (numRows < 1 || blnListsFound == false) {
$("#no_transactions").show();
$("#divTransactions").hide();
fnDoInvalidData('list', 'No data was found for this account.', true);
// $("#list").jqGrid('GridUnload');
blndoSubmit = false;
}
}
return blndoSubmit;
}
function fnValidate() {
// Validate data that has been entered by the user.
var blndoSubmit = true; // Should we submit the form?
// console.log("fnValidate() " + new Date() );
// console.log("fnValidate() called.");
fnResetInvalidFields('frmData'); // Reset the fields marked as errored.
if (!$('#chkSaveRecord').is(':checked')) {
return true;
}
$('#CompanyIds').val("");
if (!$('#chkEmailNone').is(':checked')) {
if (!fnCheckEmail($('#txtEmail').val())) {
fnDoInvalidData('txtEmail', 'Email Address is not valid.', true);
blndoSubmit = false;
}
}
var numRows = $("#list").jqGrid('getGridParam', 'records');
var selRows = $("#list").jqGrid('getGridParam', 'selarrrow');
// console.log(numRows + ' records loaded, ' + selRows.length + ' selected');
accountValidated = fnValidateAccount();
if (!accountValidated) {
// function shows no_transactions container for us
fnDoInvalidData('list', 'No data found for this account.', true);
// console.log("validateAccount gave failure.");
blndoSubmit = false;
}
var tmpselAccount = fnGetSelected('selFromAccount');
if ((tmpselAccount == '') || (tmpselAccount == '0')) {
fnDoInvalidData('selFromAccount', 'Selection required.', true);
blndoSubmit = false;
}
var tmpselAccount = fnGetSelected('selToAccount');
if ((tmpselAccount == '') || (tmpselAccount == '0')) { // swap to
fnDoInvalidData('selToAccount', 'Selection is required.', true);
blndoSubmit = false;
}
if (fnGetSelected('selFromAccount') == fnGetSelected('selToAccount')) {
fnDoInvalidData('selToAccount', 'Selections must be different.', true);
blndoSubmit = false;
}
// if undefined or no rows or no available
if (!blnListsFound) {
fnDoInvalidData('list', 'No data was found for this account.', true);
blndoSubmit = false;
}
if (!accountValidated) {
fnDoInvalidData('list', 'No data was found for this account.', true);
blndoSubmit = false;
}
if (!blnGridLoading) {
if (numRows && (typeof (selRows) === "undefined" || !selRows || !selRows.length)) {
fnDoInvalidData('list', 'At least one item must be selected.', true);
fnDoInvalidData('selFromAccount', 'At least one item must be selected.', true);
blndoSubmit = false;
}
if (numRows && (typeof (selRows) !== "undefined" && selRows && selRows.length)) {
// collect selected companyid rows from jqGrid
var aryCompanyIds = [];
for (var i = 0; i < selRows.length; i++) {
aryCompanyIds.push(
$("#list").jqGrid('getCell', selRows[i], 'Routing')
+ '=' + $("#list").jqGrid('getCell', selRows[i], 'CompanyId')
+ '=' + $("#list").jqGrid('getCell', selRows[i], 'Description')
+ '=' + $("#list").jqGrid('getCell', selRows[i], 'IndName')
);
}
// set values in hidden field
$('#CompanyIds').val(aryCompanyIds.join("||"));
}
}
else {
// grid still loading
blndoSubmit = false;
}
if (blndoSubmit === false) {
fnACHSwapGetGrid();
}
return blndoSubmit;
}
I have a bit of a bug, and I can't tell where the error comes from.
I am building a cart system that will insert multiple data to a database from a cart on submit.
I'm using AJAX for this and I'm have errors, please I need help.
Here are my code snippets:
JavaScript Code
function addSale(payment_type, cash_tendered) {
var cust_name = $("#cust_name").val();
var amt_owed = $("#amt_owed").val();
$.confirm({
title: 'Checkout',
content: '' +
'<form action="" class="formName" role="form">' +
'<div class="form-group">' +
'<label>Payment Type</label>' +
'<select id="eType" class="name form-control">' +
'<option value="cash">Cash</option>' +
'<option value="card">Card</option>' +
'</select>' +
'</div>' +
'<div class="form-group">' +
'<label>Cash Tendered</label>' +
'<input type="number" id="eCash" placeholder="Cash Tendered" class="name form-control">' +
'</div>' +
'</form>',
buttons: {
cancel: function () {
//close
},
formSubmit: {
text: 'Checkout',
btnClass: 'btn-success',
action: function () {
payment_type = this.$content.find('#eType').val();
cash_tendered = this.$content.find('#eCash').val();
if (!payment_type || !cash_tendered) {
$.alert('Please fill all fields.');
return false;
}
$.confirm({
title: 'Do you want to continue?',
type: 'orange',
content: 'Click Ok to add sale',
buttons: {
cancel: function () {
},
proceed: {
text: 'Ok',
btnClass: 'btn btn-success',
action: function () {
var addUrl = "home/addsales";
addUrl += "/" + payment_type;
addUrl += "/" + cash_tendered;
addUrl += "/" + cust_name;
addUrl += "/" + amt_owed;
//
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#eType").val("");
$("#eCash").val("");
$("#cust_name").val("");
$("#amt_owed").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
}
}
});
}
}
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
}
Here is the Home Controller Code:
private function addsales($payment_type = null, $cash_tendered = null, $cust_name = null, $amt_owed = null) {
if (isset($payment_type, $cash_tendered)) {
$email = $_SESSION[DbStrings::$EMAIL];
$payment_type = $this->test_input($payment_type);
$cash_tendered = $this->test_input($cash_tendered);
$insertedSale = $this->member->insertDailySale($email, $payment_type, $cash_tendered);
$cust_name = $this->test_input($cust_name);
$amt_owed = $this->test_input($amt_owed);
$insertedCredit = 1;
if (isset($cust_name, $amt_owed) && $amt_owed > 0) {
$insertedCredit = $this->member->insertCredit($email, $cust_name, $amt_owed);
}
if ($insertedSale && $insertedCredit) {
$_SESSION['temp_invoice'] = $_SESSION[DbStrings::$INVOICE];
$chars = "003232303232023232023456789";
srand((double) microtime() * 1000000);
$i = 0;
$pass = '';
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
$alpha = 'NM-' . $pass;
$_SESSION[DbStrings::$INVOICE] = $alpha;
echo "Your sale has been inserted succesfully";
} else {
echo "There was a problem inserting your sale. Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And Here is my Model Code that still fetches other functions:
public function insertDailySale($email, $payment_type, $cash_tendered) {
$invoice = $_SESSION[DbStrings::$INVOICE];
$this->db->from(DbStrings::$SALES_ORDER_TABLE_NAME);
$condition = array(DbStrings::$EMAIL => $email, DbStrings::$INVOICE => $invoice);
$this->db->where($condition);
$query = $this->db->get();
$checks = $query->result_array();
foreach ($checks as $queries) {
$productID = $queries[DbStrings::$PRODUCTID];
$quantity = $queries[DbStrings::$SALES_QUANTITY];
$amount = $queries[DbStrings::$SALES_AMOUNT];
$profit = $queries[DbStrings::$SALES_PROFIT];
$product_code = $queries[DbStrings::$PRODUCT_CODE];
$product_name = $queries[DbStrings::$PRODUCT_NAME];
$product_selling = $queries[DbStrings::$PRODUCT_SELLING];
$this->deductInventory($email, $product_code, $quantity);
$this->updateQuantitySold($email, $product_code, $quantity);
$cost_price = $this->product->getCostPrice($product_code);
$data[] = array(
DbStrings::$EMAIL => $email,
DbStrings::$INVOICE => $invoice,
DbStrings::$PRODUCTID => $productID,
DbStrings::$SALES_QUANTITY => $quantity,
DbStrings::$SALES_AMOUNT => $amount,
DbStrings::$SALES_PROFIT => $profit,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_CP => $cost_price,
DbStrings::$PRODUCT_SP => $product_selling,
DbStrings::$PAYMENT_TYPE => $payment_type,
DbStrings::$CASH_TENDERED => $cash_tendered,
DbStrings::$DATE_CREATED => time()
);
$inserted = $this->db->insert_batch(DbStrings::$DAILYSALES_TABLE_NAME, $data);
}
return $inserted;
}
With the above, i get flagged this error:
There was a problem inserting your sale. Please try again.
Please I need help on this.
The error came from my database structure. Being an internal server error, it came from the DB.
I realized i deleted a column from my database table, and i was still sending data to the removed column.
Thanks guys for the attempt to help.
I'm using Prestashop version 1.6.1.17 .
I have a module called "Blockcallmeback". This module adds the option to the customer to leave his/her telephone number so you can call him/her back.
The problem is that after submitting the form, there is an error that says:
"An error occured. Please check your data."
Which means, the ajax function returns success = false, but I don't know why.
This is the js code:
<script type="text/javascript">
var blockcallme_url = "/casannabis/modules/blockcallme/ajax.php";
var blockcallme_text_please = "Please enter";
var blockcallme_text_please_phone = "your phone number";
var blockcallme_text_thanks = "Thank you. We will call you soon.";
var blockcallme_text_error = "An error occured. Please check your data.";
var blockcallme_mask = "+56 (9) 9999-9999";
$(function () {
$("a.blockcallme_button").fancybox({
'hideOnContentClick': false,
'hideOnOverlayClick': true,
'overlayOpacity': 0.4,
'padding': 0,
afterShow: function () {
$('#blockcallme_phone').focus();
$('#blockcallme_phone').inputmask({
'mask': blockcallme_mask,
"clearMaskOnLostFocus": false
});
}
});
$('.blockcallme_form').on('submit', function () {
debugger;
$('#blockcallme_loader').show();
var form = $(this);
$('.blockcallme_errors').html('').hide();
$('.blockcallme_success').html('').hide();
var success = true;
var blockcallme_phone_input = $(this).find('#blockcallme_phone');
if (!blockcallme_phone_input.val() || !blockcallme_phone_input.inputmask('isComplete')) {
blockcallme_phone_input.css('outline', '1px solid red');
setTimeout(function () {
blockcallme_phone_input.css('outline', '');
}, 1000);
$(this).find('.blockcallme_errors').append(blockcallme_text_please + ' <span style="font-weight: bold;">' + blockcallme_text_please_phone + '</span>.<br>').show();
success = false;
}
if (!success) {
$('#blockcallme_loader').hide();
return false;
}
$.ajax({
type: 'POST',
url: blockcallme_url + '?ajax=1&rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data: form.serialize(),
success: function(jsonData) {
debugger;
$('#blockcallme_loader').hide();
if (jsonData['success'] == 1) {
form.find('.blockcallme_success').html(blockcallme_text_thanks).show();
}
else {
form.find('.blockcallme_errors').html(blockcallme_text_error).show();
}
}
});
return false;
});
});
</script>
And this is the php code:
<?php
include_once(dirname(__FILE__) . '/../../config/config.inc.php');
include_once(dirname(__FILE__) . '/../../init.php');
if(Tools::getValue('ajax') == 1)
{
$name = pSQL(trim(Tools::getValue('blockcallme_name', '')));
$phone = pSQL(trim(Tools::getValue('blockcallme_phone', '')));
$blockcallme = Module::getInstanceByName('blockcallme');
$success = 0;
if(!empty($phone))
{
Context::getContext()->cookie->blockcallme_phone = $phone;
Context::getContext()->cookie->blockcallme_name = $name;
$template = 'blockcallme';
$template_vars = array(
'{name}' => $name,
'{phone}' => $phone,
);
$email = Configuration::get('CALLME_EMAIL') ? Configuration::get('CALLME_EMAIL') : Configuration::get('PS_SHOP_EMAIL');
$to = array(
$email,
);
$send = Mail::Send(
Configuration::get('PS_LANG_DEFAULT'),
$template,
$blockcallme->l('Callback request', 'ajax'),
$template_vars,
$to,
null,
Configuration::get('PS_SHOP_EMAIL'),
Configuration::get('PS_SHOP_NAME'),
null,
null,
dirname(__FILE__).'/mails/'
);
if($send)
$success = 1;
}
if($success)
die(json_encode(array('success' => 1)));
else
die(json_encode(array('success' => 0)));
}
How do I Auto Capitalize all the value of my dynamic text box. I want on submit for security purposes. I used strtooper in PHP but it has an array problem. And I used auto capitalization using CSS but if the value is already submitted to database it is not working, it's still the same as the value I inputted. Anyone can help me.
main form:
<script type='text/javascript'>
/* attach a submit handler to the form */
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
var mytxt1 = [];
var mytxt2 = [];
$(".car_brand").each(function () {
mytxt1.push($(this).val());
});
$(".car_model").each(function () {
mytxt2.push($(this).val());
});
e.preventDefault();
var perfTimes = $(this).serialize();
$.post("maintenance_function.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.location.href = data.redirect;
}
}, "json");
});
});
<script>
var nitem =0;
var ntotal = 0;
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'Car Manufacturer: <input type="text" class="car_brand" id="' + nitem + '" required> ' +
'Car Model: <input type="text" class="car_model" id="' + nitem + '" required>' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem).each(function(){
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
</script>
Function form:
<?php
include('connect.php');
$mydata = $_POST["results"];
//echo $mydata;
parse_str($mydata);
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$errors = [];
if(!isset($_POST["txt1"])){
$errors[] = array(
'error_code' => 1,
'message' => 'Please add a text box.'
);
}
if(empty($errors)) {
for($i=0;$i<=count($_POST["txt1"])-1;$i++)
{
//if (trim($_POST["txt1"][$i]) != "" && trim($_POST["txt2"][$i]) != "" && trim($_POST["txt3"][$i]) != ""){
mysql_query("INSERT INTO car_maintenance VALUES ('', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."')");
//}
}
$response = array(
'message' => 'Successfully Added',
'redirect' => "car_maintenance.php"//add here
);
echo json_encode($response);
}
else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
?>
use this on the string you want to capitalize in the php file:
$newstring = ucwords(strtolower($string1));
this will create “title case,” where the first
letter of each word is in uppercase and the rest of the letters are in lowercase, hopw this is what you meant.
if you want all letters capital, use this:
$newstring = strtoupper($string1);
In css
input {text-transform:uppercase;}
In javascript
document.getElementsByTagName('input').value = document.getElementsByTagName('input').value.toUpperCase()
I am using a jQuery plugin called Stepy, which is based of the FormToWizard plugin, to allow users to complete a 10-step form.
Using the next/back attributes, I've added a function to post data between steps so the user can save their work and come back at a later day if they'd like.
One of my steps allows the user to add items to a form within an iframe (to post data to a separate table). I'd like it to function so that when the user moves between steps, the items in the iframe post to their separate table as well. Is there a way to submit the form within the iframe between steps (i.e. submit iframe sub-form when main form submits)?
I am using PHP and MySQL.
Any help you could provide would be amazing!
Javascript:
$(function() {
$('#custom').stepy({
backLabel: 'Back',
block: true,
errorImage: true,
nextLabel: 'Next',
titleClick: true,
validate: false,
legend: false,
back: function(index) {
$.post('../../process.php')
}
next: function(index) {
$.post('../../process.php')
}
});
});
HTML:
<html>
<body>
<form id="custom" name="custom">
<fieldset title="Thread 1">
<legend>description one</legend>
<label>Question A:</label>
<input type="text" id="question_a" name="question_a" class="required">
<label>Question B:</label>
<input type="text" id="question_b" name="question_b">
</fieldset>
<fieldset title="Thread 2">
<legend>description two</legend>
<iframe src="../../list_form.php" width="100%" height="300"></iframe>
</fieldset>
<fieldset title="Thread 3">
<legend>description three</legend>
<label>Question C:</label>
<input type="text" id="question_c" name="question_c" class="required">
</fieldset>
<input type="submit" class="finish" value="Finish!">
</form>
</body>
</html>
iframe
<html>
<body>
<form id="sub_form" name="sub_form">
<label>Question 1:</label>
<input type="text" id="question_1" name="question_1">
<label>Question 2:</label>
<input type="text" id="question_2" name="question_2">
</form>
</body>
</html>
stepy.js
;(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var opt = $.extend({}, $.fn.stepy.defaults, options),
$this = $(this).data('options', opt),
id = $this.attr('id');
if (id === undefined) {
id = 'stepy-' + $this.index();
$this.attr('id', id);
}
var $titlesWrapper = $('<ul/>', { id: id + '-titles', 'class': 'stepy-titles' });
if (opt.titleTarget) {
$(opt.titleTarget).html($titlesWrapper);
} else {
$titlesWrapper.insertBefore($this);
}
if (opt.validate) {
$this.append('<div class="stepy-error"/>');
}
var $steps = $this.children('fieldset'),
$step = undefined,
$legend = undefined,
description = '',
title = '';
$steps.each(function(index) {
$step = $(this);
$step
.addClass('step')
.attr('id', id + '-step-' + index)
.append('<p id="' + id + '-buttons-' + index + '" class="' + id + '-buttons"/>');
$legend = $step.children('legend');
if (!opt.legend) {
$legend.hide();
}
description = '';
if (opt.description) {
if ($legend.length) {
description = '<span>' + $legend.html() + '</span>';
} else {
$.error(id + ': the legend element of the step ' + (index + 1) + ' is required to set the description!');
}
}
title = $step.attr('title');
title = (title != '') ? '<div>' + title + '</div>': '--';
$titlesWrapper.append('<li id="' + id + '-title-' + index + '">' + title + description + '</li>');
if (index == 0) {
if ($steps.length > 1) {
methods.createNextButton.call($this, index);
}
} else {
methods.createBackButton.call($this, index);
$step.hide();
if (index < $steps.length - 1) {
methods.createNextButton.call($this, index);
}
}
});
var $titles = $titlesWrapper.children();
$titles.first().addClass('current-step');
var $finish = $this.children('.finish');
if (opt.finishButton) {
if ($finish.length) {
var isForm = $this.is('form'),
onSubmit = undefined;
if (opt.finish && isForm) {
onSubmit = $this.attr('onsubmit');
$this.attr('onsubmit', 'return false;');
}
$finish.click(function(evt) {
if (opt.finish && !methods.execute.call($this, opt.finish, $steps.length - 1)) {
evt.preventDefault();
} else {
if (isForm) {
if (onSubmit) {
$this.attr('onsubmit', onSubmit);
} else {
$this.removeAttr('onsubmit');
}
var isSubmit = $finish.attr('type') == 'submit';
if (!isSubmit && (!opt.validate || methods.validate.call($this, $steps.length - 1))) {
$this.submit();
}
}
}
});
$finish.appendTo($this.find('p:last'));
} else {
$.error(id + ': element with class name "finish" missing!');
}
}
if (opt.titleClick) {
$titles.click(function() {
var array = $titles.filter('.current-step').attr('id').split('-'), // TODO: try keep the number in an attribute.
current = parseInt(array[array.length - 1], 10),
clicked = $(this).index();
if (clicked > current) {
if (opt.next && !methods.execute.call($this, opt.next, clicked)) {
return false;
}
} else if (clicked < current) {
if (opt.back && !methods.execute.call($this, opt.back, clicked)) {
return false;
}
}
if (clicked != current) {
methods.step.call($this, (clicked) + 1);
}
});
} else {
$titles.css('cursor', 'default');
}
$steps.delegate('input[type="text"], input[type="password"]', 'keypress', function(evt) {
var key = (evt.keyCode ? evt.keyCode : evt.which);
if (key == 13) {
evt.preventDefault();
var $buttons = $(this).parent().children('.' + id + '-buttons');
if ($buttons.length) {
var $next = $buttons.children('.button right-aligned');
if ($next.length) {
$next.click();
} else {
var $finish = $buttons.children('.finish');
if ($finish.length) {
$finish.click();
}
}
}
}
});
$steps.first().find(':input:visible:enabled').first().select().focus();
});
}, createBackButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-back-' + index, href: 'javascript:void(0);', 'class': 'button left-aligned', html: opt.backLabel }).click(function() {
if (!opt.back || methods.execute.call($this, opt.back, index - 1)) {
methods.step.call($this, (index - 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, createNextButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-next-' + index, href: 'javascript:void(0);', 'class': 'button right-aligned', html: opt.nextLabel }).click(function() {
if (!opt.next || methods.execute.call($this, opt.next, index + 1)) {
methods.step.call($this, (index + 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, execute: function(callback, index) {
var isValid = callback.call(this, index + 1);
return isValid || isValid === undefined;
}, step: function(index) {
index--;
var $steps = this.children('fieldset');
if (index > $steps.length - 1) {
index = $steps.length - 1;
}
var opt = this.data('options');
max = index;
if (opt.validate) {
var isValid = true;
for (var i = 0; i < index; i++) {
isValid &= methods.validate.call(this, i);
if (opt.block && !isValid) {
max = i;
break;
}
}
}
$steps.hide().eq(max).show();
var $titles = $('#' + this.attr('id') + '-titles').children();
$titles.removeClass('current-step').eq(max).addClass('current-step');
if (this.is('form')) {
var $fields = undefined;
if (max == index) {
$fields = $steps.eq(max).find(':input:enabled:visible');
} else {
$fields = $steps.eq(max).find('.error').select().focus();
}
$fields.first().select().focus();
}
if (opt.select) {
opt.select.call(this, max + 1);
}
return this;
}, validate: function(index) {
if (!this.is('form')) {
return true;
}
var $step = this.children('fieldset').eq(index),
isValid = true,
$title = $('#' + this.attr('id') + '-titles').children().eq(index),
opt = this.data('options'),
$this = this;
$($step.find(':input:enabled').get().reverse()).each(function() {
var fieldIsValid = $this.validate().element($(this));
if (fieldIsValid === undefined) {
fieldIsValid = true;
}
isValid &= fieldIsValid;
if (isValid) {
if (opt.errorImage) {
$title.removeClass('error-image');
}
} else {
if (opt.errorImage) {
$title.addClass('error-image');
}
$this.validate().focusInvalid();
}
});
return isValid;
}
};
$.fn.stepy = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist!');
}
};
$.fn.stepy.defaults = {
back: undefined,
backLabel: '< Back',
block: false,
description: true,
errorImage: false,
finish: undefined,
finishButton: true,
legend: true,
next: undefined,
nextLabel: 'Next >',
titleClick: false,
titleTarget: undefined,
validate: false,
select: undefined
};
})(jQuery);
If you want to append Text\HTML or any other data to your iframe (which calling to a page on the same domain!) you may use:
jQuery("#iframe_id").contents().find('body').append('<div>Hello World</div>');
Full Example:
Full Example
If your iframe is on another domain you will have to use window.postMessage, which you may read about on Mozilla's docs:
Mozilla's docs
OR to take a look about my blog post about this subject.
Hope I helped,