How to load different textboxes based on url and database data? - javascript

I'm trying to control the loading of different textboxes according to the url of the page and prior settings in the database.
For example: I have a database table that looks like this:
And I'd like my page to look like that when browsing www.mysite.com/us/mypage
like that when browsing www.mysite.com/canada/mypage
like that when browsing www.mysite.com/italy/mypage
So I'm trying to understand how to design my code. Should it be addressed only on the client side, with javascript on the page load or should it be handled with the controller on the server side.
Thanks!

First off, since you already have the rules. Set it up first. Second, you need to parse the url (get the country and treat it like a slug) and feed it into the rules. Third, then just use a normal foreach loop and a condition inside (1/0 or true/false) if it needs to be printed or not. Consider this example:
<?php
// $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url1 = 'www.mysite.com/us/mypage';
$url2 = 'www.mysite.com/canada/mypage';
$url3 = 'www.mysite.com/italy/mypage';
// dummy values
// setup the rules
$rules = array(
'us' => array(
'textbox1' => 1,
'textbox2' => 1,
'textbox3' => 1,
'textbox4' => 1,
),
'canada' => array(
'textbox1' => 1,
'textbox2' => 1,
'textbox3' => 0,
'textbox4' => 0,
),
'italy' => array(
'textbox1' => 1,
'textbox2' => 0,
'textbox3' => 1,
'textbox4' => 0,
),
);
// properly parse the url
$current_url = $url2; // i just chosen canada for this example
if (!preg_match("~^(?:f|ht)tps?://~i", $current_url)) {
$current_url = "http://" . $current_url;
}
$current_url = array_filter(explode('/', parse_url($current_url, PHP_URL_PATH)));
$country = reset($current_url);
?>
<!-- after getting the slug/country, loop it with a condition -->
<form method="POST" action="">
<?php foreach($rules[$country] as $key => $value): ?>
<?php if($value == 1): ?>
<label><?php echo $key; ?></label>
<input type="text" name="<?php echo $key; ?>" /><br/>
<?php endif; ?>
<?php endforeach; ?>
<input type="submit" name="submit" />
</form>
<!-- textbox1 and textbox3 should be the only inputs in here since i picked canada -->

You have to set condition and check the value
if($isset($textbox) && $textbox==1)
{
//print the label and text box
}

Best thing is try to achive the output at server side.
I think the following code will be useful for you.
Try to get the country code from url and get the database values into $textboxA array, and run the following code.
$textboxA = array(1,1,0,1);
foreach($textboxA as $key => $value){
switch($key){
case 0: if($value) print $textbox1;
break;
case 1: if($value) print $textbox2;
break;
case 2: if($value) print $textbox3;
break;
case 3: if($value) print $textbox4;
break;
default: print "";
}
}

Related

Submit and POST "True" or "False" to a series of text questions presented one by one taken from a php array

new to forum, AJAX and JQuery. A little experience of PHP and JS.
I'm trying to present a long series of questions (400+) one by one in an input text field on a form with 2 submit buttons labelled "True" and "False". I need one question to be presented at a time, then record the True or False result as (1 or -1) sequentially into another text file. I cannot refresh the input field with the next question after 'Submit'. I believe that AJAX would be the answer.
This code is the first effort: (any later efforts are more complicated, but don't work any better) it opens the questions file (CPXQ.dat) into an indexed array, then places the first question into the input text field. When either of the submit buttons are pressed, the result is POSTed to data.cpx, and the next question appears, but it won't continue thereafter. I have tried various PHP loops and some javascript, but these don't work, either looping through immediately to the last question, or getting stuck in the loop. (The php includes just contain CSS and JQuery source.)
I'd also like to prevent the user from being able to go back over any of the questions, but that may be a query for another day!
Any advice much appreciated, and apologies if not clear. Happy to provide any further info.
<div class="container">
<?php include("top.php"); ?>
<div class="intro">
<p><h1>CPI TEST</h1></p>
<?php
$i = 0;
//file in to an array
$lines = file("CPXQ.dat");
?>
<?php
if(isset($_POST['submitT'])) {
//echo $_POST['submitT'];
$data="1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
if(isset($_POST['submitF'])) {
//echo $_POST['submitF'];
$data="-1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
?>
<form method = "post" action = "CPI_Test.php">
<input type="text" name="question" value="<?php echo $lines[$i];?>">
<input type="submit" name="submitT" value="True">
<input type="submit" name="submitF" value="False">
</form>
</div>
</body>
Here's the code for the preliminary page collecting user details:
<!DOCTYPE html>
<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PPCS CPI Information</title>
<?php include("head.php"); ?>
</head>
<body>
<?php
// define variables and set to empty values
$initdataErr = $surnamedataErr = $agedataErr = $gendataErr = "";
$initdata = $surnamedata = $agedata = $gendata = $codata = "";
function test_input(&$surnamedata) {
$surnamedata = trim($surnamedata);
$surnamedata = stripslashes($surnamedata);
//$data = htmlspecialchars($data);
$surnamedata = preg_replace('/\s+/', '', $surnamedata);
return $surnamedata;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['initdata'])) {
$initdataErr = "Initials are required";
} else {
$initdata = test_input($_POST['initdata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Z- ]*$/",$initdata)) {
$initdataErr = "Please use capital letters without spaces only";
}
}
if (empty($_POST['surnamedata'])) {
$surnamedataErr = "Surname is required";
} else {
$surnamedata = test_input($_POST['surnamedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$surnamedata)) {
$surnamedataErr = "Please use letters only";
}
}
if (empty($_POST['agedata'])) {
$agedataErr = "Age is required";
} else {
$agedata = test_input($_POST['agedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$agedata)) {
$agedataErr = "Only numbers and white space allowed";
}
}
if (empty($_POST['gendata'])) {
$gendataErr = "Gender is required";
}
}
?>
<div class="container">
<?php include("top.php"); ?>
<br><h1>CPI TEST INFORMATION</h1><br>
<b>Please fill in the form below carefully</b>
<p><span class="error">* required field</span></p>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Initials: <span class="error">* <?php echo $initdataErr;?></span> <br>
<input type="text" name="initdata" value="<?php echo $initdata;?>"><br>
<br>
Surname: <span class="error">* <?php echo $surnamedataErr;?></span> <br>
<input type="text" name="surnamedata" value="<?php echo $surnamedata;?>" ><br>
<br>
Company (Optional):<br>
<input type="text" name="codata" value="<?php echo isset($_POST["codata"]) ? $_POST["codata"] : '';?>" ><br>
<br>
Age in Years: <span class="error">* <?php echo $agedataErr;?></span><br>
<input type="text" name="agedata" maxlength="2" min="0" max="99" step="1" pattern="[0-9]{2}"value="<?php echo $agedata;?>"><br>
<br>
Gender: <span class="error">* <?php echo $gendataErr;?></span><br>
<select name="gendata">
<option value="">Select...</option>
<option value="m" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'm') ? 'selected' : ''; ?>>Male</option>
<option value="f" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'f') ? 'selected' : ''; ?>>Female</option>
</select>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit'])){
// Fetching variables of the form which travels in URL
$initdata = $_POST['initdata'];
$surnamedata = $_POST['surnamedata'];
$codata = $_POST['codata'];
$agedata = $_POST['agedata'];
$gendata = $_POST['gendata'];
if($initdata !=''&&(preg_match("/^[A-Z]*$/",$initdata))
&& $surnamedata !='' && (preg_match("/^([A-Za-z \-]+(?:\'|&#0*39;)*)*[A-Za-z \-]+$/",$surnamedata)) && $agedata !='' && (preg_match("/^[0-9]*$/",$agedata)) && $gendata !='')
{
date_default_timezone_set("Europe/London");
//^['\a-zA-Z]*$/ This is the most recent
test_input($surnamedata);
$_POST['surnamedata'] = ucwords($_POST['surnamedata']);
$data = '"' . $_POST['initdata'] . ' ' . stripslashes($_POST['surnamedata']) . '","' . $_POST['agedata'] . '","'. $_POST['gendata'] .'","' . $_POST['codata'] . '","' . '","'. '","'. date("d/m/Y"). '","'. date("H:i:s"). '","';
//Create CPX filename
$fn = $_POST['initdata'] . $_POST['surnamedata'];
$fn = preg_replace('/\PL/u', '', $fn);
$fn = strtoupper($fn);
$fn = $fn . "XXXXXX";
$fn = substr($fn,0,8);
echo "$fn";
echo "$data";
//Create temp file for CPX filename
$fp = fopen($fn . '.temp', 'a') or die("Unable to open file!");
fwrite($fp, $fn);
fclose($fp);
//Create CPX file
$fp = fopen($fn . '.cpx', 'a') or die("Unable to open file!");
fwrite($fp, $data);
//Append new line
//fwrite($fp, "\ntest");
fclose($fp);
// Redirect
/header("Location:/CPI_Form_Trial/instructions.php");
}
else{
?>
<br><span class = "error"><?php echo "Please make sure that you have filled in all required fields and click 'Submit' again";?></span> <?php
}
}
?>
Using AJAX (fetch) is ideally suited to this type of problem where you do not wish to refresh the screen and want to present new data after submitting a http request. The following single page application shows how you might accomplish your stated goal but it does not take into account a couple of possible issues which are:
[a] multiple users participating in the questionnaire simultaneously
[b] a user abandoning the questionnaire and restarting, once or more than once.
The issues mentioned could be negated by using a database to store answers and assigning the users unique identifiers (ie: user id, username) which is used when sending the ajax request.
The demo that follows will write, to the answerfile, either 1 or 0 ( which is more common than -1 for false ) alongside the question line number ( which is sort of the ID )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
$file='CPXQ.dat';
$answerfile='data.cpx';
$lines=file( $file );
switch( $_POST['action'] ){
case 'start':
header('Content-Type: text/html');
exit( $lines[0] );
break;
case 'question':
$id=(int)$_POST['id'];
# increment ID value
$id++;
$question=isset( $lines[ $id ] ) ? $lines[ $id ] : false;
if( $question && $id < count( $lines ) ){
# log the current answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
# the json payload
$data=array(
'id' => $id,
'question' => $question
);
} elseif( !$question && $id==count( $lines ) ){
# log the final answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
$data=array(
'id' => 0,
'question' => 'End of questionnaire'
);
}
header('Content-Type: application/json');
exit( json_encode( $data ) );
break;
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Questions, questions, questions...</title>
</head>
<body>
<!--
a basic form: The question is rendered within the `fieldset`
element. Both buttons use datasets, the data-id refers to the
question number (line from source file) and data-value is the
boolean value indicating answer value.
-->
<form name='questions' method='post'>
<fieldset></fieldset>
<div>
<input type='button' data-value=1 data-id=0 value='True' />
<input type='button' data-value=0 data-id=0 value='False' />
</div>
</form>
<script>
const fs=document.querySelector('fieldset');
/*
When the page loads we fetch the first question ( ie: first line in source file )
and display on the page. The action parameter helps the backend determine what stage
we are at.
*/
let fd=new FormData();
fd.set('action', 'start');
// make the request an show question
fetch( location.href, { method:'post', body:fd })
.then(r=>r.text())
.then(text=>{
fs.innerHTML=text;
});
/*
The delegated event handler processes button clicks and sends the
data-id ( ie: line number ) and answer to the backend processing script.
Here this is all done on the same page for convenience - for your case
it would be CPI_Test.php
*/
const clickhandler=function(e){
if( e.target.tagName.toLowerCase()=='input' && e.target.type=='button' ){
// set a different `action` so that the backend knows what to do
fd.set('action','question');
fd.set('id',e.target.dataset.id);
fd.set('answer',e.target.dataset.value);
// send the request and display new question
fetch( location.href, { method:'post', body:fd } )
.then( r=>r.json() )
.then( json=>{
fs.innerHTML=json.question;
// update the buttons so that they have the new id assigned ready for next click
// or disable ( or remove ) when the questionnaire is over.
document.querySelectorAll('[type="button"][data-value]').forEach( bttn=>{
if( Number( json.id ) !==0 ) bttn.dataset.id=json.id;
else bttn.disabled=true;
});
})
}
};
// add a delegated event handler to process button clicks
document.forms.questions.addEventListener( 'click', clickhandler );
</script>
</body>
</html>
A sample of the answerfile:
q:1, a:1
q:2, a:0
q:3, a:1
q:4, a:1
q:5, a:0
q:6, a:0
q:7, a:1
q:8, a:0
q:9, a:1
q:10, a:0
q:11, a:1
q:12, a:1
q:13, a:1
q:14, a:1
q:15, a:0
q:16, a:1
q:17, a:0
q:18, a:1
q:19, a:1
q:20, a:0
I hope it helps you arrive at a solution but as mentioned it would be more robust / reliable with a database rather than simple text file.

How do I pass JavaScript variables to PHP in yii2?

I am developing a recriment software and in Yii2 framework application form I want to check if applicant has already applied for same job using 'passport no', my form looks like
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'cnic')->textInput(['type' => 'number']) ?>
<?= Html::submitButton('Save and Continue', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
and I am unable to get the cnic value in php. my Javascript code is.
$('#applications-cnic').change(function(){
var data = $(this).val();
var validation = <?= $model->checkCNIC($postid, '<script>data</script>'?>. <?= ) ?>;
alert(validation);
if (validation == 'data_exist') {
alert("You have already applied for this job, use your tracking ID to check your applicaiton or contact HR");
}
});
it is not working and I am unable to pass this value I get from javascript to my php function.
public function checkCNIC($value , $cnic)
{
$query= Applications::find()
->where(['post_id' => $value])
->andWhere(['cnic' => $cnic])
->all();
if ($query) {
return 'data_exist';
}
else
return 'no_data';
}
Ajax is the recommended solution. You can still use javascript inside php using document.writeln
'<script>document.writeln(data)</script>`

How to POST multiple pages of same data

first page was registration.php
on pay.php
<form action="success.php" method="post">
<input type="hidden" value=<?php echo json_encode($_POST); ?> custom="Hidden Element" name="customer">
</form>
on success.php
I am not getting any values
<?php
$_POST['customer'] = json_decode($_POST['customer'],true);
echo $_POST['customer']['name']; //prints nothing
?>
Instead of passing your data back to the frontend, create a session on the server in which your data is temporarily stored across all pages.
When a session is started you can access and set your values by using the $_SESSION global variable. This variable is available across all of your files once a session is started and will hold hold your values until the session ends.
// Check if there is an active session.
// Otherwise start it.
if ( ! session_id() ) {
session_start();
}
// Receive and store.
$customer = $_POST[ 'customer' ]
$_SESSION[ 'customer' ] = $customer;
// Just to show what is in the session.
echo json_decode( $_SESSION[ 'customer' ] );
And if you're finished and you want to end the session on the last page then use session_destroy() to remove the entire session. Another option is to just let the session timeout and remove itself.
<?php
$data = ["name"=>"Thomas O'Leary"];
$encoded = json_encode($data);
//$encoded = bin2hex($encoded);
var_dump($_POST);
if(isset($_POST['data'])) {
$data = $_POST['data'];
//$data = hex2bin($data);
$data = json_decode($data, true);
var_dump($data);
}
?>
<form method='post'>
<input type='hidden' name='data' value='<?= $encoded ?>'>
<input type='submit'>
</form>
Upon form submission, you'll get this output:
array(1) { ["data"]=> string(17) "{"name":"Thomas O" } NULL
Indicating data loss, and invalid json.
This is because of the quotes in the hidden field value:
<input type='hidden' name='data' value='{"name":"Thomas O'Leary"}'>
If you use double quotes for the attribute, you can imagine also running into issues.
So the quotes need some kind of escaping/encoding.
If you uncomment the bin2hex and hex2bin lines above, you'll get the output:
array(1) { ["data"]=> string(50) "7b226e616d65223a2254686f6d6173204f274c65617279227d" } array(1) { ["name"]=> string(14) "Thomas O'Leary" }
Some use htmlentities($data, ENT_QUOTES); or base64_encode($data) as another workaround.

Convert single quotes to apostrophes on form submit in PHP

Is there a way to convert left and right single quotes into apostrophes when a form is submitted and before validation begins?
The reason I ask is that my form works on all platforms just how I want it, however iPhone users at times use the wrong character and input a left or right single quotation instead. As my form verifies the entered data and must be exact, the left single quote is being seen as a error compared to the apostrophe in the DB table and not accepting the information.
If I could have those characters convert when the user submits to apostrophes then all would work even on the iPhones. any insight would be gratefully appreciated, I have tried a few items like htmlspecialchar but didn't seem to assist.
Also I should note that when using the iPhone and entering the coorect apostrophe in the smart keyboard layout on ios11 I was able to successfully pass validation of the form. It seems this is a known issue of apples but they have yet to rectify this, I am sure the solution would be beneficial to many in the community I hope, if we can find the answer that is.
The form field in question is:
<input type="text" name="last_name" id="last_name" value="<?php echo htmlspecialchars(stripslashes(isset($fields['last_name'])) ? $fields['last_name'] : '') ?>" >
how can I set this form field to convert left and right single quotes into apostrophes on form submit using php or jquery?
UPDATE
#fubar you are my savior tonight. the first solution worked great. But how would I add teh second option instead?
function cv(&$fields, &$errors) {
// Check args and replace if necessary
if (!is_array($fields)) $fields = array();
if (!is_wp_error($errors)) $errors = new WP_Error;
// Check for form submit
if (isset($_POST['submit'])) {
// Get fields from submitted form
$fields = cv_get_fields();
// Validate fields and produce errors
if (cv_validate($fields, $errors)) {
// If successful, display a message
$Id=$fields['login'];
$First=$fields['first_name'];
$Last=$fields['last_name'];
global $wpdb;
$user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM users WHERE login = %s", $Id ) );
$userquery = $wpdb->get_results($user->login);
$Id=$fields['login'];
if ( !username_exists ($Id)) {
$Id=$fields['login'];
$access = $wpdb->get_row( $wpdb->prepare( "SELECT access FROM table WHERE ID = %s", $Id ) );
foreach ($access as $accessquery) {
if ($accessquery == lvl2) {
$_SESSION['mem_data']=$fields;
header("Location: https://example.com/lvl2-register/");
}
if ( is_null ($accessquery)) {
$_SESSION['mem_data']=$fields;
header("Location: https://example.com/lvl1-register/");
}
}
}
elseif ( username_exists ($Id)) {
header("Location: https://example.com/already-registered/");
}
}
}
// Santitize fields
cv_sanitize($fields);
// Generate form
cv_display_form($fields, $errors);
}
function cv_sanitize(&$fields) {
$fields['login'] = isset($fields['login']) ? sanitize_user($fields['login']) : '';
$fields['first_name'] = isset($fields['first_name']) ? sanitize_text_field($fields['first_name']) : '';
$fields['last_name'] = isset($fields['last_name']) ? sanitize_text_field($fields['last_name']) : '';
}
function cv_display_form($fields = array(), $errors = null) {
// Check for wp error obj and see if it has any errors
if (is_wp_error($errors) && count($errors->get_error_messages()) > 0) {
// Display errors
?>
<div class="step1-form" style="display:block;margin:0 auto;text-align:left;max-width:1080px;">
<?php
foreach ($errors->get_error_messages() as $key => $val) {
?><p>
<?php echo $val; ?>
</p><?php
}
?><?php
}
// Display form
?>
</div>
<div class="step1-form" style="display:block;margin:0 auto;text-align:left;max-width:1080px;">
<h1 class="til-postheader entry-title">User Registration: Step 1 of 2</h1>
<h4>Prior to registering for this website you must first verify Your Membership.<h4>
<div id="login" style="max-width:175px;width:100%;margin:10px;">
<form action="" method="post">
<div>
<label for="first_name">First Name:</label><br>
<input type="text" name="first_name" id="first_name" value="<?php echo (isset($fields['first_name']) ? $fields['first_name'] : '') ?>" >
</div>
<br>
<div>
<label for="last_name">Last Name:</label><br>
<input type="text" name="last_name" id="last_name" value="<?php echo htmlspecialchars(stripslashes(isset($fields['last_name'])) ? $fields['last_name'] : '') ?>" >
</div>
<br>
<div>
<a data-fancybox data-src="#ID" href="javascript:;" style="outline:none;border:0px;text-decoration:none;" tabindex="-1"><span style="width:21px;float:right;color:#ffffff;background:#0a4b73;text-align:center;line-height:21px;border-radius:50%;" tabindex="-1">?</span></a><label for="login">Member ID:</label><br>
<input type="text" name="login" id="login" value="<?php echo (isset($fields['login']) ? $fields['login'] : '') ?>" >
</div>
<br>
<input type="submit" name="submit" value="Verify Membership">
</form>
</div>
<?php
}
function cv_get_fields() {
return array(
'login' => isset($_POST['login']) ? $_POST['login'] : '',
'first_name' => isset($_POST['first_name']) ? $_POST['first_name'] : '',
'last_name' => isset($_POST['last_name']) ? $_POST['last_name'] : '',
);
}
function cv_validate(&$fields, &$errors) {
// Make sure there is a proper wp error obj
// If not, make one
if (!is_wp_error($errors)) $errors = new WP_Error;
// Validate form data
// Define $Card $First $Last $PIN
$Id=$fields['login'];
$First=$fields['first_name'];
$Last=$fields['last_name'];
// $Lastname = htmlspecialchars_decode(stripslashes($fields["last_name"]));
$Lastname = '‘ ‘ - ’ ’';
$Lastname = str_replace(['‘', '’'], "'", html_entity_decode(stripslashes($fields["last_name"])));
global $wpdb;
$result = $wpdb->get_row( $wpdb->prepare( 'SELECT distinct ID, First, Last, FROM table WHERE ID = %s AND First = "%s" AND Last = "%s", $Id, $First, $Lastname ) );
if ( is_null ( $result ) ) {
$errors->add('non_member', 'The information entered does not match our records.');
}
if (empty($fields['login']) || empty($fields['first_name']) || empty($fields['last_name'])) {
$errors->add('field', '');
}
// If errors were produced, fail
if (count($errors->get_error_messages()) > 0) {
return false;
}
$Id=$fields['login'];
global $wpdb;
$accessno = $wpdb->get_row( $wpdb->prepare( "SELECT distinct access FROM table WHERE ID = %s", $Id ) );
foreach ($accessno as $noquery) {
if ( $noquery == NO) {
header ('Location: https://example.com/access-denied/');
}
}
// Else, success!
return true;
}
// The callback function for the [cv] shortcode
function cv_cb() {
$fields = array();
$errors = new WP_Error();
// Buffer output
ob_start();
// Custom verification, go!
cv($fields, $errors);
// Return buffer
return ob_get_clean();
}
add_shortcode('cv', 'cv_cb');
This would convert the single quote, both raw and encoded into apostrophes.
$value = '‘ ‘ - ’ ’';
$value = str_replace(['‘', '’'], "'", html_entity_decode($value));
If you want to apply this to all POST data, you could use:
$_POST = array_map(function ($value) {
return str_replace(['‘', '’'], "'", html_entity_decode($value));
}, $_POST);
Edit
If you replace the following line:
// Get fields from submitted form
$fields = cv_get_fields();
With:
// Get fields from submitted form
$fields = array_map(function ($value) {
return str_replace(['‘', '’'], "'", html_entity_decode($value));
}, cv_get_fields());
And then you can remove the following:
$Lastname = '‘ ‘ - ’ ’';
$Lastname = str_replace(['‘', '’'], "'", html_entity_decode(stripslashes($fields["last_name"])));

CodeIgniter Dynamic rows from JavaScript table entries

I am trying to grab my post data from my view and have it there on page reload (after it passes through validation), I am really struggling with this as I am only just learning JavaScript so anything dynamic to my is completely new...
What the data looks like in a print_R():
Array ( [firstname] => [lastname] => [address1] => [address2] => [addressSuburb] => [addressState] => [addressPostcode] => [email] => [addressCountry] => AU [orderRef] => [orderNote] => [orderTrack] => [counter0] => 0 [itemCode0] => 1234 [Desc0] => Test1 [Qty0] => 1 [Cost0] => 5 [counter1] => 1 [itemCode1] => 5678 [Desc1] => Test 2 [Qty1] => 2 [Cost1] => 10 [create] => Create Order )
What my current view loops look like:
<?php if($this->input->post()):?>
<?php foreach($this->input->post('counter') as $counter): ?>
<tr>
<?php foreach($this->input->post() + $counter AS $key => $value): ?>
<td>
<input type="text" name="<?php echo $key + $counter ?>" value="<?php echo $value ?>"/>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endif; ?>
The Error I am getting:
Severity: Warning
Message: Invalid argument supplied for foreach()
I assume its because counter isnt actually an array, just part of it... I dont know how to output each line of entry data into its own array, then it would actually be rather easy to do...
Please don't give me a hard time for having it all in the view, as I am learning heaps easier to have it centralized there while trying to get an output.

Categories