Creating export and import in codeigniter i need an assistant - javascript

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

Related

How do I submit form without page reload taking into consideration the php script?

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

Send 2 variables through url

I send 2 variables by url:
var http = false;
http = new XMLHttpRequest();
function carrega(){
var nome = document.getElementById('CodigoUtente').value;
var nomes = document.getElementById('Nome').value;
var url_="conexao4?CodigoUtente="+nome+"&Nome="+nomes;
http.open("GET",url_,true);
http.onreadystatechange=function(){
if(http.readyState==4){
var retorno = JSON.parse(http.responseText);
document.getElementById('CodigoUtente').value = retorno.CodigoUtente;
document.getElementById('Nome').value = retorno.Nome;
document.getElementById('DataNasc').value = retorno.DataNasc;
document.getElementById('Sexo').value = retorno.Sexo;
document.getElementById('Estadocivil').value = retorno.Estadocivil;
document.getElementById('Nacionalidade').value = retorno.Nacionalidade;
document.getElementById('Responsavel').value = retorno.Responsavel;
document.getElementById('Parentesco').value = retorno.Parentesco;
document.getElementById('Contato').value = retorno.Contato;
}
}
http.send(null);
}
in the connection page4 I have the php that receives the variables:
$CodigoUtente = $_GET['CodigoUtente'];
$Nome = $_GET['Nome'];
if((isset($CodigoUtente)) && (isset($Nome))){
$query= "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes WHERE (CodigoUtente = '$CodigoUtente') OR (Nome LIKE '%$Nome%')";
$resultados = $conn->query($query);
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
The problem is that they only work if you fill in the two inputs and intended that they return the data from the database only when filling one of them.
Curious_Mind was saying this way?
$where_caluse = array();
if(isset($_GET['CodigoUtente'])){
$where_caluse[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where_caluse[] = "Nome = '".$_GET['Nome']."'";
}
$where = array_filter($where_caluse);
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
$resultados = $conn->query($query);
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$query = "$query WHERE ". $final_where;
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
I tried to apply the form it said, but it is not working, it gives 500 error when I send the values ​​of the variables.
Can you help fix the problem? I have a form to be populated with these values
$where = " where ";
$CodigoUtente = 'a';
$Nome = '';
if($CodigoUtente != '' && $Nome != '')
{
$where .= "CodigoUtente = '$CodigoUtente' OR Nome = '$Nome';";
}else if ($CodigoUtente != ''){
$where .= "CodigoUtente = '$CodigoUtente';";
}else{
$where .= " Nome = '$Nome';";
}
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes".$where;
echo $query;
You can try like this way before making you sql query. This will help you to handle WHERE with OR condition, without OR condition and without any condition at all.
$where = array();
$_GET['CodigoUtente'] = 'Sany';
$_GET['Nome'] = 'Bruno';
if(isset($_GET['CodigoUtente'])){
$where[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where[] = "Nome = '".$_GET['Nome']."'";
}
$sql = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$sql = "$sql WHERE ". $final_where;
}
echo $sql;
DEMO: https://3v4l.org/phZGW

I can not get data from jQuery muscles

I am learning tutorial, but I understand that the author made a mistake / mistakes.
The data is sent via GET in php and write, but do not turn back.
JavaScript:
function loadAllPost() {
var divs = $("#posts");
$.get("twitor.php?action=last", function() {
var posts = [];
for(var i = 0; i < posts.length; i++) {
var newPost = addNewPost(posts[i].name, posts[i].text, posts[i].date);
posts.push(newPost);
}
divs.children().remove();
divs.append(posts);
});
}
$(function() {
loadAllPost();
setInterval(loadAllPost, 5000);
$("#submit").click(function() {
var newPostName = $("#name").val();
var newPostText = $("#text").val();
var newPostDate = (new Date()).toLocaleString();
var newPost = addNewPost(newPostName, newPostText, newPostDate);
newPost.hide();
$("#posts").append(newPost);
newPost.slideToggle();
$("name").val("");
$("text").val("");
$.post("twitor.php?action=new", {
text: newPostText,
name: newPostName
});
});
});
Ie like php sends data, but does not have JS embeds them in HTML.
PHP:
if ($_GET['action'] == 'new') {
addNewPost();
}
elseif ($_GET['action'] == 'last') {
getLastPosts();
}
function getPDO(){
$db_host = "****";
$db_name = "****";
$db_user = "****";
$db_pass = "****";
$PDO = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
return $PDO;
}
function addNewPost(){
$params = [];
$params['name'] = $_POST['name'];
$params['text'] = htmlspecialchars($_POST['text']);
$PDO = getPDO();
$Statement = $PDO->prepare("INSERT INTO posts(`name`, `text`, `date`) VALUES (:name, :text, NOW());");
$Statement->execute($params);
}
function getLastPosts() {
$PDO = getPDO();
$Statement = $PDO->query("SELECT * FROM posts ORDER BY date DESC LIMIT 15");
if(!$Statement) return;
$posts = $Statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($posts);
}

Restrict Date/Time Picker

I'm using the contact form 7 datepicker plugin which works great but i'm looking to limit the values on it: https://wordpress.org/plugins/contact-form-7-datepicker/.
I want for users to be able to use the date picker on my contact form 7 booking forms but i want them to only be able to select a day that is no earlier than 1 day and 1 hour in advance. So if i try to select todays date and todays time, an alert will popup saying that its too early. It has to be 25 hours at the earliest. How would i even begin this with the below plugin code:
time.php file ...
<?php
class ContactForm7Datepicker_Time {
static $inline_js = array();
public static function register() {
// Register shortcodes
add_action('wpcf7_init', array(__CLASS__, 'add_shortcodes'));
// Validations
add_filter('wpcf7_validate_time', array(__CLASS__, 'validation_filter'), 10, 2);
add_filter('wpcf7_validate_time*', array(__CLASS__, 'validation_filter'), 10, 2);
// Tag generator
add_action('load-contact_page_wpcf7-new', array(__CLASS__, 'tag_generator'));
add_action('load-toplevel_page_wpcf7', array(__CLASS__, 'tag_generator'));
// Messages
add_filter('wpcf7_messages', array(__CLASS__, 'messages'));
// Print inline javascript
add_action('wp_print_footer_scripts', array(__CLASS__, 'print_inline_js'), 99999);
}
public static function shortcode_handler($tag) {
$tag = new WPCF7_Shortcode($tag);
if (empty($tag->name))
return '';
$validation_error = wpcf7_get_validation_error($tag->name);
$class = wpcf7_form_controls_class($tag->type, 'wpcf7-date');
if ($validation_error)
$class .= ' wpcf7-not-valid';
$atts = array();
$atts['size'] = $tag->get_size_option('40');
$atts['maxlength'] = $tag->get_maxlength_option();
$atts['class'] = $tag->get_class_option($class);
$atts['id'] = $tag->get_option('id', 'id', true);
$atts['tabindex'] = $tag->get_option('tabindex', 'int', true);
$atts['type'] = 'text';
if ($tag->has_option('readonly'))
$atts['readonly'] = 'readonly';
if ($tag->is_required())
$atts['aria-required'] = 'true';
$value = (string)reset($tag->values);
if ($tag->has_option('placeholder') || $tag->has_option('watermark')) {
$atts['placeholder'] = $value;
$value = '';
}
if (wpcf7_is_posted() && isset($_POST[$tag->name]))
$value = stripslashes_deep($_POST[$tag->name]);
$atts['value'] = $value;
$dpOptions = array();
$dpOptions['timeFormat'] = str_replace('_', ' ', $tag->get_option('time-format', '', true));
$dpOptions['firstDay'] = (int)$tag->get_option('first-day', 'int', true);
$dpOptions['showAnim'] = $tag->get_option('animate', '', true);
$dpOptions['controlType'] = $tag->get_option('control-type', '', true);
$dpOptions['showButtonPanel'] = $tag->has_option('buttons');
$dpOptions['changeMonth'] = $tag->has_option('change-month');
$dpOptions['changeYear'] = $tag->has_option('change-year');
foreach (array('minute', 'hour', 'second') as $s) {
foreach (array('min', 'max') as $m) {
$dpOptions[$s . ucfirst($m)] = (int)$tag->get_option("$m-$s", 'int', true);
}
$dpOptions['step' . ucfirst($s)] = (int)$tag->get_option("step-$s", 'int', true);
}
$inline = $tag->has_option('inline');
if ($inline) {
$dpOptions['altField'] = "#{$tag->name}_alt";
$atts['id'] = "{$tag->name}_alt";
}
$atts['type'] = $inline ? 'hidden' : '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 %4$s</span>',
$tag->name, $atts, $validation_error,
$inline ? "<div id=\"{$tag->name}_timepicker\"></div>" : '');
$html = apply_filters('cf7dp_time_input', $html);
$dp_selector = $inline ? '#' . $tag->name . '_timepicker' : $tag->name;
$dp = new CF7_DateTimePicker('time', $dp_selector, $dpOptions);
self::$inline_js[] = $dp->generate_code($inline);
return $html;
}
public static function validation_filter($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
$value = trim($_POST[$name]);
if ('time*' == $type && empty($value)) {
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message('invalid_required');
}
if (! empty($value) && ! self::is_valid_date($value)) {
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message('invalid_time');
}
return $result;
}
public static function tag_generator() {
if (! function_exists( 'wpcf7_add_tag_generator'))
return;
wpcf7_add_tag_generator('time',
__('Time field', 'wpcf7'),
'wpcf7-tg-pane-time',
array(__CLASS__, 'tg_pane')
);
}
public static function tg_pane() {
require_once dirname(__FILE__) . '/generators/time.php';
}
public static function add_shortcodes() {
if (function_exists('wpcf7_add_shortcode')) {
wpcf7_add_shortcode(array('time', 'time*'), array(__CLASS__, 'shortcode_handler'), true);
}
}
public static function messages($messages) {
$messages['invalid_time'] = array(
'description' => __('The time that the sender entered is invalid'),
'default' => __('Invalid time supplied.'),
);
return $messages;
}
public static function print_inline_js() {
if (! wp_script_is('jquery-ui-timepicker', 'done') || empty(self::$inline_js))
return;
$out = implode("\n\t", self::$inline_js);
$out = "jQuery(function($){\n\t$out\n});";
echo "\n<script type=\"text/javascript\">\n{$out}\n</script>\n";
}
private static function animate_dropdown() {
$html = "<select id=\"animate\">\n";
foreach (CF7_DateTimePicker::$effects as $val) {
$html .= '<option value="' . esc_attr($val) . '">' . ucfirst($val) . '</option>';
}
$html .= "</select>";
echo $html;
}
private static function is_valid_date($value) {
$valid = strtotime($value) ? true : false;
return apply_filters( 'cf7dp_is_valid_time', $valid, $value );
}
}
ContactForm7Datepicker_Time::register();
date.php ...
<?php
class ContactForm7Datepicker_Date {
static $inline_js = array();
public static function register() {
// Register shortcodes
add_action('wpcf7_init', array(__CLASS__, 'add_shortcodes'));
remove_filter('wpcf7_validate_date', 'wpcf7_date_validation_filter', 10);
remove_filter('wpcf7_validate_date*', 'wpcf7_date_validation_filter', 10);
remove_filter('wpcf7_messages', 'wpcf7_date_messages');
remove_action('admin_init', 'wpcf7_add_tag_generator_date', 19);
// Validations
add_filter('wpcf7_validate_date', array(__CLASS__, 'validation_filter'), 10, 2);
add_filter('wpcf7_validate_date*', array(__CLASS__, 'validation_filter'), 10, 2);
// Tag generator
add_action('load-contact_page_wpcf7-new', array(__CLASS__, 'tag_generator'));
add_action('load-toplevel_page_wpcf7', array(__CLASS__, 'tag_generator'));
// Messages
add_filter('wpcf7_messages', array(__CLASS__, 'messages'));
// Print inline javascript
add_action('wp_print_footer_scripts', array(__CLASS__, 'print_inline_js'), 99999);
}
public static function shortcode_handler($tag) {
$tag = new WPCF7_Shortcode($tag);
if (empty($tag->name))
return '';
$validation_error = wpcf7_get_validation_error($tag->name);
$class = wpcf7_form_controls_class($tag->type, 'wpcf7-date');
if ($validation_error)
$class .= ' wpcf7-not-valid';
$atts = array();
$atts['size'] = $tag->get_size_option('40');
$atts['maxlength'] = $tag->get_maxlength_option();
$atts['class'] = $tag->get_class_option($class);
$atts['id'] = $tag->get_option('id', 'id', true);
$atts['tabindex'] = $tag->get_option('tabindex', 'int', true);
$atts['type'] = 'text';
if ($tag->has_option('readonly'))
$atts['readonly'] = 'readonly';
if ($tag->is_required())
$atts['aria-required'] = 'true';
$value = (string)reset($tag->values);
if ($tag->has_option('placeholder') || $tag->has_option('watermark')) {
$atts['placeholder'] = $value;
$value = '';
}
if (wpcf7_is_posted() && isset($_POST[$tag->name]))
$value = stripslashes_deep($_POST[$tag->name]);
$atts['value'] = $value;
$dpOptions = array();
$dpOptions['dateFormat'] = str_replace('_', ' ', $tag->get_option('date-format', '', true));
$dpOptions['minDate'] = $tag->get_option('min-date', '', true);
$dpOptions['maxDate'] = $tag->get_option('max-date', '', true);
$dpOptions['firstDay'] = (int)$tag->get_option('first-day', 'int', true);
$dpOptions['showAnim'] = $tag->get_option('animate', '', true);
$dpOptions['yearRange'] = str_replace('-', ':', $tag->get_option('year-range', '', true));
$dpOptions['numberOfMonths'] = (int)$tag->get_option('months', 'int', true);
$dpOptions['showButtonPanel'] = $tag->has_option('buttons');
$dpOptions['changeMonth'] = $tag->has_option('change-month');
$dpOptions['changeYear'] = $tag->has_option('change-year');
$dpOptions['noWeekends'] = $tag->has_option('no-weekends');
$inline = $tag->has_option('inline');
if ($inline) {
$dpOptions['altField'] = "#{$tag->name}_alt";
$atts['id'] = "{$tag->name}_alt";
}
$atts['type'] = $inline ? 'hidden' : '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 %4$s</span>',
$tag->name, $atts, $validation_error,
$inline ? "<div id=\"{$tag->name}_datepicker\"></div>" : '');
$html = apply_filters('cf7dp_date_input', $html);
$dp_selector = $inline ? '#' . $tag->name . '_datepicker' : $tag->name;
$dp = new CF7_DateTimePicker('date', $dp_selector, $dpOptions);
self::$inline_js[] = $dp->generate_code($inline);
return $html;
}
public static function validation_filter($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
$value = trim($_POST[$name]);
if ('date*' == $type && empty($value)) {
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message('invalid_required');
}
if (! empty($value) && ! self::is_valid_date($value)) {
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message('invalid_date');
}
return $result;
}
public static function tag_generator() {
if (! function_exists( 'wpcf7_add_tag_generator'))
return;
wpcf7_add_tag_generator('date',
__('Date field', 'wpcf7'),
'wpcf7-tg-pane-date',
array(__CLASS__, 'tg_pane')
);
}
public static function tg_pane() {
require_once dirname(__FILE__) . '/generators/date.php';
}
public static function add_shortcodes() {
if (function_exists('wpcf7_add_shortcode')) {
// Remove Contact Form 7's date module
wpcf7_remove_shortcode('date');
wpcf7_remove_shortcode('date*');
wpcf7_add_shortcode(array('date', 'date*'), array(__CLASS__, 'shortcode_handler'), true);
}
}
public static function messages($messages) {
$messages['invalid_date'] = array(
'description' => __('The date that the sender entered is invalid'),
'default' => __('Invalid date supplied.'),
);
return $messages;
}
public static function print_inline_js() {
if (! wp_script_is('jquery-ui-datepicker', 'done') || empty(self::$inline_js))
return;
$out = implode("\n\t", self::$inline_js);
$out = "jQuery(function($){\n\t$out\n});";
echo "\n<script type=\"text/javascript\">\n{$out}\n</script>\n";
}
private static function animate_dropdown() {
$html = "<select id=\"animate\">\n";
foreach (CF7_DateTimePicker::$effects as $val) {
$html .= '<option value="' . esc_attr($val) . '">' . ucfirst($val) . '</option>';
}
$html .= "</select>";
echo $html;
}
private static function is_valid_date($value) {
$valid = strtotime($value) ? true : false;
if (! $valid) {
// Validate dd/mm/yy
$new_value = str_replace('/', '-', $value);
$valid = strtotime($new_value) ? true : false;
}
return apply_filters( 'cf7dp_is_valid_date', $valid, $value );
}
}
ContactForm7Datepicker_Date::register();
I used the shortcodes within contact form 7 for this, i.e. min-day:1. Hope this helps someone else.

using jquery to loads result into pages

I have got a php databse query which I am trying to process with jquery to loads pages, at the moment when i try and test nothing happens so I feel that the problem lies within my HTMLoutput within the jquery script where I am trying to carry out a php explode function could anyone shed some light on this?
here is the php code to parse the data:
if (!$db_server){
die("unable to Connect to MYSQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
if(trim($_POST['submit']) =="submit"){
}else{
if (isset($_POST['dropoption']) && ($_POST['dropoption'] != '')){
if (isset($_POST['meal']) && ($_POST['meal'] != '')) {
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9#', '', $_POST['last']);
$pn = preg_replace('#[^0-9#', '', $_POST['pn']);
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last){
$pn = $last;
}
include_once("db_connect.php");
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
$sql = "SELECT * FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal' $limit";
$query = mysqli_query($db_server, $sql);
$datastring = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$mealname = $row["mealname"];
$mealpic = $row["imagepath"];
$cookingtime = $row["minutes"]."minutes".$row["hours"]."hours";
$ingredients = $row["ingredients"];
$recipe = $row["recipe"];
$datastring .= $mealname.'|'.$mealpic.'|'.$cookingtime.'|'.$ingredients.'|'.$recipe.'||';
}
echo $datastring;
exit();
}
$dropoption = clean_string($db_server, $_POST['dropoption']);
$meal = clean_string($db_server, $_POST['meal']);
$quer = "SELECT COUNT(recipeid) FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal'";
mysqli_select_db($db_server, $db_database);
$querya= mysqli_query($db_server, $quer);
if (!$querya) die("database access failed: " . mysqli_error($db_server));
$row = mysqli_fetch_row($querya);
$total_rows = $row[0];
$rpp = 1;
$last = ceil($total_rows/$rpp);
if(last < 1){
$last = 1;
}
}//if(meal)//
}//if(cuisine)//
} //if(trim)//
}
?>
And here is the jquery script:
<script type="text/javascript">
var rpp=<?php echo $rpp; ?>;
var last=<?php echo $last; ?>;
function request_page(pn) {
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results";
var hr = new XMLHttpRequest();
hr.open("POST", "results.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urleconded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText split("||");
var html_output = "";
for(i= 0; i< dataArray.length - 1; i++) {
var itemArray = dataArray[i].split("|");
html_output += "Recipe: "+itemArray[0]+"<img src='http://ml11maj.icsnewmedia.net/Workshops/Week%207/"+itemArray[1]+"'/><h2>Ingredients</h2><?php $ingredientchunks = (explode(",","+itemArray[2]+"));
for($i = 1; $i < count($ingredientchunks); $i++){
echo "$i.$ingredientchunks[$i] <br/>";}?>"+itemArray[3]+"<h2>Recipe</h2>
<?php $recipechunks = (explode(",","+itemArray[4]+"));
for($i = 1; $i < count($recipechunks); $i++){
echo "$i.$recipechunks[$i] </br>";}
?>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
//change pagination controls//
var paginationCtrls = "";
if(last !=1) {
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn !=last) {
paginationCtrls += '< <button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
Yep, I suspect it's your explode(",","+itemArray[2]+") that's causing the problem.
Explode is used to split strings into arrays, like so:
$string = "Apples,Oranges,Pears";
$array = explode(",",$string);
var_dump($array);
Example Output
array(2)
(
[0] => string(5) "Apples"
[1] => string(6) "Oranges"
[2] => string(4) "Pears"
)

Categories

Resources