Using Custom Datepicker NMR plugin with CF7 which nearly duplicate the CF7 date.php module and add a new $tag where we can use jquery-ui-datepicker.
Everything works as except but when the field is required, the validation do not validate the datepicker field on form submit.
Looks like this line have no effect :
**$atts['aria-invalid'] = $validation_error ? 'true' : 'false';**
Any help would be appreciated !
Thanks in advance
[PHP]
add_action('wpcf7_init', 'nmr_add_jqueryui_datepicker');
function nmr_add_jqueryui_datepicker()
{
wpcf7_add_form_tag(
array('datepicker', 'datepicker*'),
'nmr_datepicker_form_tag_handler',
array('name-attr' => true)
);
}
function nmr_datepicker_form_tag_handler($tag)
{
if (empty($tag->name)) {
return '';
}
$validation_error = wpcf7_get_validation_error($tag->name);
$class = wpcf7_form_controls_class($tag->type);
$class .= ' wpcf7-validates-as-date';
if ($validation_error) {
$class .= ' wpcf7-not-valid';
}
$atts = array();
$atts['class'] = $tag->get_class_option($class) . ' nmr-datepicker';
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option('tabindex', 'signed_int', true);
$atts['min'] = $tag->get_date_option('min');
$atts['max'] = $tag->get_date_option('max');
$atts['step'] = $tag->get_option('step', 'int', true);
$atts['data-format'] = $tag->get_option('format', '', true);
if ($tag->has_option('readonly')) {
$atts['readonly'] = 'readonly';
}
if ($tag->is_required()) {
$atts['aria-required'] = 'true';
}
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$value = (string) reset($tag->values);
if (
$tag->has_option('placeholder')
or $tag->has_option('watermark')
) {
$atts['placeholder'] = $value;
$value = '';
}
$value = $tag->get_default_option($value);
$value = wpcf7_get_hangover($tag->name, $value);
$atts['value'] = $value;
$atts['type'] = 'text';
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts($atts);
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><input %2$s />%3$s</span>',
sanitize_html_class($tag->name),
$atts,
$validation_error
);
return $html;
}
function nmr_datepicker_enqueue_script() {
$path = plugin_dir_url( __FILE__ );
wp_enqueue_style('jquery-ui-css', $path .'css/jquery-ui.css');
wp_enqueue_script( 'nmr_datepicker', $path . 'js/nmr-datepicker.js' , array('jquery', 'jquery-ui-datepicker'));
}
add_action('wp_enqueue_scripts', 'nmr_datepicker_enqueue_script');
[JS]
(function ($) {
$(document).ready(function () {
$(".nmr-datepicker").each(function (i, item) {
var settings = {};
if (item.dataset.format) {
settings.dateFormat = item.dataset.format;
}
if (item.id) {
$(`#${item.id}`).datepicker(settings);
}
});
});
})(jQuery);
**$atts['aria-invalid'] = $validation_error ? 'true' : 'false';**
I think the problem here is:-
"$atts['aria-invalid'] = $validation_error" - taken as ternary argument
it should be:-
$atts['aria-invalid'] = ( $validation_error ? 'true' : 'false' );
So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
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;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
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);
}
//qis_process_application in register.php
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);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
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);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
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: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
Just wondering if anyone has any idea how to fix this error as I'm not sure. I'm aware there are similar questions but their full error is different.
Full Error HERE:
Fatal error: Uncaught Stripe\Error\InvalidRequest: Must provide source or customer. in /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/ApiRequestor.php:110 from API request 'req_N9vZa4brfYHaam' Stack trace: #0 /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/ApiRequestor.php(275): Stripe\ApiRequestor->handleApiError('{\n "error": {\n...', 400, Array, Array) #1 /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/ApiRequestor.php(65): Stripe\ApiRequestor->_interpretResponse('{\n "error": {\n...', 400, Array) #2 /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/ApiResource.php(120): Stripe\ApiRequestor->request('post', '/v1/charges', Array, Array) #3 /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/ApiResource.php(159): Stripe\ApiResource::_staticRequest('post', '/v1/charges', Array, NULL) #4 /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/Charge.php(74): Stripe\ApiResource::_create(Array, NULL) #5 /customers/8/7/b/exammarked.com/httpd.www/charge.php(17): Stripe\Charge::create(Array) #6 {main} throw in /customers/8/7/b/exammarked.com/httpd.www/stripe/lib/ApiRequestor.php on line 110
index.js
'use strict';
var stripe = Stripe('*****');
function registerElements(elements, exampleName) {
var formClass = '.' + exampleName;
var example = document.querySelector(formClass);
var form = example.querySelector('form');
var resetButton = example.querySelector('a.reset');
var error = form.querySelector('.error');
var errorMessage = error.querySelector('.message');
function enableInputs() {
Array.prototype.forEach.call(
form.querySelectorAll(
"input[type='text'], input[type='email'], input[type='tel']"
),
function(input) {
input.removeAttribute('disabled');
}
);
}
function disableInputs() {
Array.prototype.forEach.call(
form.querySelectorAll(
"input[type='text'], input[type='email'], input[type='tel']"
),
function(input) {
input.setAttribute('disabled', 'true');
}
);
}
function triggerBrowserValidation() {
// The only way to trigger HTML5 form validation UI is to fake a user submit
// event.
var submit = document.createElement('input');
submit.type = 'submit';
submit.style.display = 'none';
form.appendChild(submit);
submit.click();
submit.remove();
}
// Listen for errors from each Element, and show error messages in the UI.
var savedErrors = {};
elements.forEach(function(element, idx) {
element.on('change', function(event) {
if (event.error) {
error.classList.add('visible');
savedErrors[idx] = event.error.message;
errorMessage.innerText = event.error.message;
} else {
savedErrors[idx] = null;
// Loop over the saved errors and find the first one, if any.
var nextError = Object.keys(savedErrors)
.sort()
.reduce(function(maybeFoundError, key) {
return maybeFoundError || savedErrors[key];
}, null);
if (nextError) {
// Now that they've fixed the current error, show another one.
errorMessage.innerText = nextError;
} else {
// The user fixed the last error; no more errors.
error.classList.remove('visible');
}
}
});
});
// Listen on the form's 'submit' handler...
form.addEventListener('submit', function(e) {
e.preventDefault();
// Trigger HTML5 validation UI on the form if any of the inputs fail
// validation.
var plainInputsValid = true;
Array.prototype.forEach.call(form.querySelectorAll('input'), function(
input
) {
if (input.checkValidity && !input.checkValidity()) {
plainInputsValid = false;
return;
}
});
if (!plainInputsValid) {
triggerBrowserValidation();
return;
}
// Show a loading screen...
example.classList.add('submitting');
// Disable all inputs.
disableInputs();
// Gather additional customer data we may have collected in our form.
var name = form.querySelector('#' + exampleName + '-name');
var address1 = form.querySelector('#' + exampleName + '-address');
var city = form.querySelector('#' + exampleName + '-city');
var state = form.querySelector('#' + exampleName + '-state');
var zip = form.querySelector('#' + exampleName + '-zip');
var additionalData = {
name: name ? name.value : undefined,
address_line1: address1 ? address1.value : undefined,
address_city: city ? city.value : undefined,
address_state: state ? state.value : undefined,
address_zip: zip ? zip.value : undefined,
};
// Use Stripe.js to create a token. We only need to pass in one Element
// from the Element group in order to create a token. We can also pass
// in the additional customer data we collected in our form.
stripe.createToken(elements[0], additionalData).then(function(result) {
// Stop loading!
example.classList.remove('submitting');
if (result.token) {
// If we received a token, show the token ID.
example.querySelector('.token').innerText = result.token.id;
example.classList.add('submitted');
} else {
// Otherwise, un-disable inputs.
enableInputs();
}
});
});
resetButton.addEventListener('click', function(e) {
e.preventDefault();
// Resetting the form (instead of setting the value to `''` for each input)
// helps us clear webkit autofill styles.
form.reset();
// Clear each Element.
elements.forEach(function(element) {
element.clear();
});
// Reset error state as well.
error.classList.remove('visible');
// Resetting the form does not un-disable inputs, so we need to do it separately:
enableInputs();
example.classList.remove('submitted');
});
}
Other JS file:
(function() {
'use strict';
var stripe = Stripe('*****');
var elements = stripe.elements();
var elementStyles = {
base: {
color: '#555',
fontWeight: 400,
fontSize: '15px',
fontSmoothing: 'antialiased',
':focus': {
color: '#424770',
},
'::placeholder': {
color: '#555',
},
':focus::placeholder': {
color: '#CFD7DF',
},
},
invalid: {
color: '#555',
':focus': {
color: '#FA755A',
},
'::placeholder': {
color: '#FFCCA5',
},
},
};
var elementClasses = {
focus: 'focus',
empty: 'empty',
invalid: 'invalid',
};
var cardNumber = elements.create('cardNumber', {
style: elementStyles,
classes: elementClasses,
placeholder: "Card Number",
});
cardNumber.mount('#example3-card-number');
var cardExpiry = elements.create('cardExpiry', {
style: elementStyles,
classes: elementClasses,
placeholder: "Expiry (MM/YY)",
});
cardExpiry.mount('#example3-card-expiry');
var cardCvc = elements.create('cardCvc', {
style: elementStyles,
classes: elementClasses,
placeholder: "Security Code (CVC)",
});
cardCvc.mount('#example3-card-cvc');
registerElements([cardNumber, cardExpiry, cardCvc], 'example3');
})();
APIRESOURCE.PHP
<?php
namespace Stripe;
/**
* Class ApiResource
*
* #package Stripe
*/
abstract class ApiResource extends StripeObject
{
private static $HEADERS_TO_PERSIST = array('Stripe-Account' => true, 'Stripe-Version' => true);
public static function baseUrl()
{
return Stripe::$apiBase;
}
/**
* #return ApiResource The refreshed resource.
*/
public function refresh()
{
$requestor = new ApiRequestor($this->_opts->apiKey, static::baseUrl());
$url = $this->instanceUrl();
list($response, $this->_opts->apiKey) = $requestor->request(
'get',
$url,
$this->_retrieveOptions,
$this->_opts->headers
);
$this->setLastResponse($response);
$this->refreshFrom($response->json, $this->_opts);
return $this;
}
/**
* #return string The name of the class, with namespacing and underscores
* stripped.
*/
public static function className()
{
$class = get_called_class();
// Useful for namespaces: Foo\Charge
if ($postfixNamespaces = strrchr($class, '\\')) {
$class = substr($postfixNamespaces, 1);
}
// Useful for underscored 'namespaces': Foo_Charge
if ($postfixFakeNamespaces = strrchr($class, '')) {
$class = $postfixFakeNamespaces;
}
if (substr($class, 0, strlen('Stripe')) == 'Stripe') {
$class = substr($class, strlen('Stripe'));
}
$class = str_replace('_', '', $class);
$name = urlencode($class);
$name = strtolower($name);
return $name;
}
/**
* #return string The endpoint URL for the given class.
*/
public static function classUrl()
{
$base = static::className();
return "/v1/${base}s";
}
/**
* #return string The instance endpoint URL for the given class.
*/
public static function resourceUrl($id)
{
if ($id === null) {
$class = get_called_class();
$message = "Could not determine which URL to request: "
. "$class instance has invalid ID: $id";
throw new Error\InvalidRequest($message, null);
}
$id = Util\Util::utf8($id);
$base = static::classUrl();
$extn = urlencode($id);
return "$base/$extn";
}
/**
* #return string The full API URL for this API resource.
*/
public function instanceUrl()
{
return static::resourceUrl($this['id']);
}
protected static function _validateParams($params = null)
{
if ($params && !is_array($params)) {
$message = "You must pass an array as the first argument to Stripe API "
. "method calls. (HINT: an example call to create a charge "
. "would be: \"Stripe\\Charge::create(array('amount' => 100, "
. "'currency' => 'usd', 'card' => array('number' => "
. "4242424242424242, 'exp_month' => 5, 'exp_year' => 2015)))\")";
throw new Error\Api($message);
}
}
protected function _request($method, $url, $params = array(), $options = null)
{
$opts = $this->_opts->merge($options);
list($resp, $options) = static::_staticRequest($method, $url, $params, $opts);
$this->setLastResponse($resp);
return array($resp->json, $options);
}
protected static function _staticRequest($method, $url, $params, $options)
{
$opts = Util\RequestOptions::parse($options);
$requestor = new ApiRequestor($opts->apiKey, static::baseUrl());
list($response, $opts->apiKey) = $requestor->request($method, $url, $params, $opts->headers);
foreach ($opts->headers as $k => $v) {
if (!array_key_exists($k, self::$HEADERS_TO_PERSIST)) {
unset($opts->headers[$k]);
}
}
return array($response, $opts);
}
protected static function _retrieve($id, $options = null)
{
$opts = Util\RequestOptions::parse($options);
$instance = new static($id, $opts);
$instance->refresh();
return $instance;
}
protected static function _all($params = null, $options = null)
{
self::_validateParams($params);
$url = static::classUrl();
list($response, $opts) = static::_staticRequest('get', $url, $params, $options);
$obj = Util\Util::convertToStripeObject($response->json, $opts);
if (!is_a($obj, 'Stripe\\Collection')) {
$class = get_class($obj);
$message = "Expected type \"Stripe\\Collection\", got \"$class\" instead";
throw new Error\Api($message);
}
$obj->setLastResponse($response);
$obj->setRequestParams($params);
return $obj;
}
protected static function _create($params = null, $options = null)
{
self::_validateParams($params);
$url = static::classUrl();
list($response, $opts) = static::_staticRequest('post', $url, $params, $options);
$obj = Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* #param string $id The ID of the API resource to update.
* #param array|null $params
* #param array|string|null $opts
*
* #return ApiResource the updated API resource
*/
protected static function _update($id, $params = null, $options = null)
{
self::_validateParams($params);
$url = static::resourceUrl($id);
list($response, $opts) = static::_staticRequest('post', $url, $params, $options);
$obj = Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
protected function _save($options = null)
{
$params = $this->serializeParameters();
if (count($params) > 0) {
$url = $this->instanceUrl();
list($response, $opts) = $this->_request('post', $url, $params, $options);
$this->refreshFrom($response, $opts);
}
return $this;
}
protected function _delete($params = null, $options = null)
{
self::_validateParams($params);
$url = $this->instanceUrl();
list($response, $opts) = $this->_request('delete', $url, $params, $options);
$this->refreshFrom($response, $opts);
return $this;
}
}
APIREQUESTOR.PHP
<?php
namespace Stripe;
/**
* Class ApiRequestor
*
* #package Stripe
*/
class ApiRequestor
{
private $_apiKey;
private $_apiBase;
private static $_httpClient;
public function __construct($apiKey = null, $apiBase = null)
{
$this->_apiKey = $apiKey;
if (!$apiBase) {
$apiBase = Stripe::$apiBase;
}
$this->_apiBase = $apiBase;
}
private static function _encodeObjects($d)
{
if ($d instanceof ApiResource) {
return Util\Util::utf8($d->id);
} elseif ($d === true) {
return 'true';
} elseif ($d === false) {
return 'false';
} elseif (is_array($d)) {
$res = array();
foreach ($d as $k => $v) {
$res[$k] = self::_encodeObjects($v);
}
return $res;
} else {
return Util\Util::utf8($d);
}
}
/**
* #param string $method
* #param string $url
* #param array|null $params
* #param array|null $headers
*
* #return array An array whose first element is an API response and second
* element is the API key used to make the request.
*/
public function request($method, $url, $params = null, $headers = null)
{
if (!$params) {
$params = array();
}
if (!$headers) {
$headers = array();
}
list($rbody, $rcode, $rheaders, $myApiKey) =
$this->_requestRaw($method, $url, $params, $headers);
$json = $this->_interpretResponse($rbody, $rcode, $rheaders);
$resp = new ApiResponse($rbody, $rcode, $rheaders, $json);
return array($resp, $myApiKey);
}
/**
* #param string $rbody A JSON string.
* #param int $rcode
* #param array $rheaders
* #param array $resp
*
* #throws Error\InvalidRequest if the error is caused by the user.
* #throws Error\Authentication if the error is caused by a lack of
* permissions.
* #throws Error\Permission if the error is caused by insufficient
* permissions.
* #throws Error\Card if the error is the error code is 402 (payment
* required)
* #throws Error\RateLimit if the error is caused by too many requests
* hitting the API.
* #throws Error\Api otherwise.
*/
public function handleApiError($rbody, $rcode, $rheaders, $resp)
{
if (!is_array($resp) || !isset($resp['error'])) {
$msg = "Invalid response object from API: $rbody "
. "(HTTP response code was $rcode)";
throw new Error\Api($msg, $rcode, $rbody, $resp, $rheaders);
}
$error = $resp['error'];
$msg = isset($error['message']) ? $error['message'] : null;
$param = isset($error['param']) ? $error['param'] : null;
$code = isset($error['code']) ? $error['code'] : null;
switch ($rcode) {
case 400:
// 'rate_limit' code is deprecated, but left here for backwards compatibility
// for API versions earlier than 2015-09-08
if ($code == 'rate_limit') {
throw new Error\RateLimit($msg, $param, $rcode, $rbody, $resp, $rheaders);
}
// intentional fall-through
case 404:
throw new Error\InvalidRequest($msg, $param, $rcode, $rbody, $resp, $rheaders);
case 401:
throw new Error\Authentication($msg, $rcode, $rbody, $resp, $rheaders);
case 402:
throw new Error\Card($msg, $param, $code, $rcode, $rbody, $resp, $rheaders);
case 403:
throw new Error\Permission($msg, $rcode, $rbody, $resp, $rheaders);
case 429:
throw new Error\RateLimit($msg, $param, $rcode, $rbody, $resp, $rheaders);
default:
throw new Error\Api($msg, $rcode, $rbody, $resp, $rheaders);
}
}
private static function _formatAppInfo($appInfo)
{
if ($appInfo !== null) {
$string = $appInfo['name'];
if ($appInfo['version'] !== null) {
$string .= '/' . $appInfo['version'];
}
if ($appInfo['url'] !== null) {
$string .= ' (' . $appInfo['url'] . ')';
}
return $string;
} else {
return null;
}
}
private static function _defaultHeaders($apiKey)
{
$appInfo = Stripe::getAppInfo();
$uaString = 'Stripe/v1 PhpBindings/' . Stripe::VERSION;
$langVersion = phpversion();
$uname = php_uname();
$httplib = 'unknown';
$ssllib = 'unknown';
if (function_exists('curl_version')) {
$curlVersion = curl_version();
$httplib = 'curl ' . $curlVersion['version'];
$ssllib = $curlVersion['ssl_version'];
}
$appInfo = Stripe::getAppInfo();
$ua = array(
'bindings_version' => Stripe::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'stripe',
'uname' => $uname,
'httplib' => $httplib,
'ssllib' => $ssllib,
);
if ($appInfo !== null) {
$uaString .= ' ' . self::_formatAppInfo($appInfo);
$ua['application'] = $appInfo;
}
$defaultHeaders = array(
'X-Stripe-Client-User-Agent' => json_encode($ua),
'User-Agent' => $uaString,
'Authorization' => 'Bearer ' . $apiKey,
);
return $defaultHeaders;
}
private function _requestRaw($method, $url, $params, $headers)
{
$myApiKey = $this->_apiKey;
if (!$myApiKey) {
$myApiKey = Stripe::$apiKey;
}
if (!$myApiKey) {
$msg = 'No API key provided. (HINT: set your API key using '
. '"Stripe::setApiKey(<API-KEY>)". You can generate API keys from '
. 'the Stripe web interface. See https://stripe.com/api for '
. 'details, or email support#stripe.com if you have any questions.';
throw new Error\Authentication($msg);
}
$absUrl = $this->_apiBase.$url;
$params = self::_encodeObjects($params);
$defaultHeaders = $this->_defaultHeaders($myApiKey);
if (Stripe::$apiVersion) {
$defaultHeaders['Stripe-Version'] = Stripe::$apiVersion;
}
if (Stripe::$accountId) {
$defaultHeaders['Stripe-Account'] = Stripe::$accountId;
}
$hasFile = false;
$hasCurlFile = class_exists('\CURLFile', false);
foreach ($params as $k => $v) {
if (is_resource($v)) {
$hasFile = true;
$params[$k] = self::_processResourceParam($v, $hasCurlFile);
} elseif ($hasCurlFile && $v instanceof \CURLFile) {
$hasFile = true;
}
}
if ($hasFile) {
$defaultHeaders['Content-Type'] = 'multipart/form-data';
} else {
$defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
$combinedHeaders = array_merge($defaultHeaders, $headers);
$rawHeaders = array();
foreach ($combinedHeaders as $header => $value) {
$rawHeaders[] = $header . ': ' . $value;
}
list($rbody, $rcode, $rheaders) = $this->httpClient()->request(
$method,
$absUrl,
$rawHeaders,
$params,
$hasFile
);
return array($rbody, $rcode, $rheaders, $myApiKey);
}
private function _processResourceParam($resource, $hasCurlFile)
{
if (get_resource_type($resource) !== 'stream') {
throw new Error\Api(
'Attempted to upload a resource that is not a stream'
);
}
$metaData = stream_get_meta_data($resource);
if ($metaData['wrapper_type'] !== 'plainfile') {
throw new Error\Api(
'Only plainfile resource streams are supported'
);
}
if ($hasCurlFile) {
// We don't have the filename or mimetype, but the API doesn't care
return new \CURLFile($metaData['uri']);
} else {
return '#'.$metaData['uri'];
}
}
private function _interpretResponse($rbody, $rcode, $rheaders)
{
$resp = json_decode($rbody, true);
$jsonError = json_last_error();
if ($resp === null && $jsonError !== JSON_ERROR_NONE) {
$msg = "Invalid response body from API: $rbody "
. "(HTTP response code was $rcode, json_last_error() was $jsonError)";
throw new Error\Api($msg, $rcode, $rbody);
}
if ($rcode < 200 || $rcode >= 300) {
$this->handleApiError($rbody, $rcode, $rheaders, $resp);
}
return $resp;
}
public static function setHttpClient($client)
{
self::$_httpClient = $client;
}
private function httpClient()
{
if (!self::$_httpClient) {
self::$_httpClient = HttpClient\CurlClient::instance();
}
return self::$_httpClient;
}
}
CHARGE.PHP
<?php
//include Stripe library
require_once ('./stripe/init.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_jfrwNbzP7kUm6kbXSHHDkqce");
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
'amount' => 999,
'currency' => 'usd',
'description' => 'Example charge',
'source' => $token,
]);
?>
table name: emp
column name: (emp_name, emp_salry,emp_city,emp_country)
column values:("ali","2000","Multan","Pakistan")
i have an array
$info = array(
'emp_name'=>'Ali',
"emp_salery"=> '2000',
"emp_city"=> 'Multan',
"emp_country"=> "Pakistan"
);
I want to call a function
insert($info,"emp");
which return the answer in the browser as follow
insert into emp (emp_name,emp_salery,emp_city,emp_country) value("ali",'2000','multan', "Pakistan");
What is the solution using loops?
function insert($info,$table){
$qry = "";
$fields = "";
$values = "";
foreach($info as $field => $value){
$fields.=$field.",";
$values.="'".$value."',";
}
$qry.="insert into ".$table." (".rtrim($fields,',').") value (".rtrim($values,',').")";
return $qry;
}
$info = array(
"emp_name" => "Ali",
"emp_salery" => "2000",
"emp_city" => "Multan",
"emp_country"=> "Pakistan"
);
echo insert($info,"emp");
Try this
$info = array(
'emp_name'=>'Ali',
"emp_salery"=> '2000',
"emp_city"=> 'Multan',
"emp_country"=> "Pakistan");
$tblname = "emp";
print_r(insert($info,$tblname));
function insert($info,$tblname){
$q = "insert into ".$tblname ."(";
$keys ="";
$val = "";
foreach($info as $key=>$value){
$keys .= $key.",";
$val .= "'".$value."',";
}
$keys = rtrim($keys, ',');
$val =rtrim($val, ',');
$q .= $keys.") value(".$val.")";
return $q;
}
Output
insert into emp(emp_name,emp_salery,emp_city,emp_country) value('Ali','2000','Multan','Pakistan')
you can use the following function
$array_col=array_keys($info);
$array_val=array_values($info);
function get_insert_syntax($table,$info){
$cols="insert into $table(";
$vals="values (";
for($i=0;$i<count($info);$i++)
{
if($i<(count($a)-1)){
$cols.=$array_col[$i].',';
$vals.="'".$array_val[$i]."',";
}
else{
$cols.=$array_col[$i].')';
$vals.="'".$array_val[$i]."')";
}
}
return $cols.' '.$vals;
}
$info = array(
'emp_name'=>'Ali',
"emp_salery"=> '2000',
"emp_city"=> 'Multan',
"emp_country"=> "Pakistan"
);
$table="emp";
function get_insert_syntax($table,$info){
$array_col=array_keys($info);
$array_val=array_values($info);
$cols="insert into $table(";
$vals="values (";
for($i=0;$i<count($info);$i++)
{
if($i<(count($info)-1)){
$cols.=$array_col[$i].',';
$vals.="'".$array_val[$i]."',";
}
else{
$cols.=$array_col[$i].')';
$vals.="'".$array_val[$i]."')";
}
}
echo $cols.' '.$vals;
}
get_insert_syntax($table,$info);
I need an assistant with creating export and import file in codeigniter, I am not advanced in coding, I am still learning. I didn't add export button as I also need an assistant on how to add it
Here is my view
<form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
<input type="file" name="userfile" size="10" style="width:20px;">
<input type="submit" name="submit" value="IMPORT" class="btn btn-primary">
</form>
Here is my controller
/****MANAGE MEMBERS*****/
function member($param1 = '', $param2 = '', $param3 = '') {
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($param1 == 'create') {
$data['names'] = $this->input->post('names');
$data['surname'] = $this->input->post('surname');
$data['title'] = $this->input->post('title');
$data['initials'] = $this->input->post('initials');
$data['id_number'] = $this->input->post('id_number');
$data['passport'] = $this->input->post('passport');
$data['birthdate'] = $this->input->post('birthdate');
$data['gender'] = $this->input->post('gender');
$data['email'] = $this->input->post('email');
$data['address_1'] = $this->input->post('address_1');
$data['address_2'] = $this->input->post('address_2');
$data['address_3'] = $this->input->post('address_3');
$data['province'] = $this->input->post('province');
$data['country'] = $this->input->post('country');
$data['postal_code'] = $this->input->post('postal_code');
$data['phone'] = $this->input->post('phone');
$data['tel'] = $this->input->post('tel');
$data['country'] = $this->input->post('country');
$data['region'] = $this->input->post('region');
$data['branch'] = $this->input->post('branch');
$data['creation_timestamp'] = $this->input->post('creation_timestamp');
$data['expiry_timestamp'] = $this->input->post('expiry_timestamp');
$data['beneficiary_name'] = $this->input->post('beneficiary_name');
$data['beneficiary_surname'] = $this->input->post('beneficiary_surname');
$data['beneficiary_id_number'] = $this->input->post('beneficiary_id_number');
$data['beneficiary_phone'] = $this->input->post('beneficiary_phone');
$data['message'] = $this->input->post('message');
$data['chat_status'] = $this->input->post('chat_status');
$this->db->insert('member', $data);
$member_id = mysql_insert_id();
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/member_image/' . $member_id . '.jpg');
$this->email_model->account_opening_email('member', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
redirect(base_url() . 'index.php?admin/member/', 'refresh');
}
if ($param1 == 'do_update') {
$data['names'] = $this->input->post('names');
$data['surname'] = $this->input->post('surname');
$data['title'] = $this->input->post('title');
$data['initials'] = $this->input->post('initials');
$data['id_number'] = $this->input->post('id_number');
$data['passport'] = $this->input->post('passport');
$data['birthdate'] = $this->input->post('birthdate');
$data['gender'] = $this->input->post('gender');
$data['email'] = $this->input->post('email');
$data['address_1'] = $this->input->post('address_1');
$data['address_2'] = $this->input->post('address_2');
$data['address_3'] = $this->input->post('address_3');
$data['province'] = $this->input->post('province');
$data['country'] = $this->input->post('country');
$data['postal_code'] = $this->input->post('postal_code');
$data['phone'] = $this->input->post('phone');
$data['tel'] = $this->input->post('tel');
$data['country'] = $this->input->post('country');
$data['region'] = $this->input->post('region');
$data['branch'] = $this->input->post('branch');
$data['creation_timestamp'] = $this->input->post('creation_timestamp');
$data['expiry_timestamp'] = $this->input->post('expiry_timestamp');
$data['beneficiary_name'] = $this->input->post('beneficiary_name');
$data['beneficiary_surname'] = $this->input->post('beneficiary_surname');
$data['beneficiary_id_number'] = $this->input->post('beneficiary_id_number');
$data['beneficiary_phone'] = $this->input->post('beneficiary_phone');
$data['message'] = $this->input->post('message');
$data['chat_status'] = $this->input->post('chat_status');
$this->db->where('member_id', $param2);
$this->db->update('member', $data);
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/member_image/' . $param2 . '.jpg');
redirect(base_url() . 'index.php?admin/member/', 'refresh');
} else if ($param1 == 'personal_profile') {
$page_data['personal_profile'] = true;
$page_data['current_member_id'] = $param2;
} else if ($param1 == 'edit') {
$page_data['edit_data'] = $this->db->get_where('member', array(
'member_id' => $param2
))->result_array();
}
if ($param1 == 'delete') {
$this->db->where('member_id', $param2);
$this->db->delete('member');
redirect(base_url() . 'index.php?admin/member/', 'refresh');
}
$page_data['teachers'] = $this->db->get('member')->result_array();
$page_data['page_name'] = 'member';
$page_data['page_title'] = get_phrase('manage_member');
$this->load->view('index', $page_data);
if (!this->load->importcsv()); {
$data['memberbook'] = $this->csv_model->get_memberbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('index', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'names'=>$row['names'],
'surname'=>$row['surname'],
'initials'=>$row['initials'],
'id_number'=>$row['id_number'],
'passport'=>$row['passport'],
'birthdate'=>$row['birthdate'],
'gender'=>$row['gender'],
'phone'=>$row['phone'],
'email'=>$row['email'],
'address_1'=>$row['address_2'],
'address_2'=>$row['address_2'],
'address_3'=>$row['address_3'],
'province'=>$row['province'],
'country'=>$row['country'],
'postal_code'=>$row['postal_code'],
'tel'=>$row['tel'],
'region'=>$row['region'],
'branch'=>$row['branch'],
'creation_timestamp'=>$row['creation_timestamp'],
'expiry_timestamp'=>$row['expiry_timestamp'],
'beneficiary_name'=>$row['beneficiary_name'],
'beneficiary_surname'=>$row['beneficiary_surname'],
'beneficiary_id_number'=>$row['beneficiary_id_number'],
'beneficiary_phone'=>$row['beneficiary_phone'],
'message'=>$row['message'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
After months with this problem i came up a solution so i thought i should share it for some peeps who are having same difficulties
CONTROLLER
function member_bulk_add($param1 = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($param1 == 'import_excel')
{
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/import.xlsx');
// Importing excel sheet for bulk student uploads
include 'simplexlsx.php';
$xlsx = new SimpleXLSX('assets/import.xlsx');
list($num_cols, $num_rows) = $xlsx->dimension();
$f = 0;
foreach( $xlsx->rows() as $r )
{
// Ignore the inital name row of excel file
if ($f == 0)
{
$f++;
continue;
}
for( $i=0; $i < $num_cols; $i++ )
{
if ($i == 0) $data['name'] = $r[$i];
else if ($i == 1) $data['birthday'] = $r[$i];
else if ($i == 2) $data['sex'] = $r[$i];
else if ($i == 3) $data['address'] = $r[$i];
else if ($i == 4) $data['phone'] = $r[$i];
else if ($i == 5) $data['email'] = $r[$i];
}
$data['member_id'] = $this->input->post('member_id');
$this->db->insert('member' , $data);
//print_r($data);
}
redirect(base_url() . 'index.php?admin/member/' . $this->input->post('member_id'), 'refresh');
$this->load->view('backend/index', $page_data);
}