Correctly Passing data from Controller to View CodeIgniter - php

This question may be asked numerous times but I am facing difficulty in doing so.
var_dump($lex_post_data); works fine on controller
My Controller code
try{
// need for the manage functionality to be initialized.
$manage_mode = FALSE;
$appointment = array();
$provider = array();
$customer = array();
$lex_post_data = $this->input->post('lexname');
var_dump($lex_post_data);
// Load the book appointment view.
$view = array (
'available_services' => $available_services,
'available_providers' => $available_providers,
'company_name' => $company_name,
'manage_mode' => $manage_mode,
'appointment_data' => $appointment,
'provider_data' => $provider,
'customer_data' => $customer,
'post_data' => $lex_post_data
);
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book', $view);
View Code:
<script type="text/javascript">
var GlobalVariables = {
availableServices : <?php echo json_encode($available_services); ?>,
availableProviders : <?php echo json_encode($available_providers); ?>,
baseUrl : <?php echo '"' . $this->config->item('base_url') . '"'; ?>,
manageMode : <?php echo ($manage_mode) ? 'true' : 'false'; ?>,
appointmentData : <?php echo json_encode($appointment_data); ?>,
providerData : <?php echo json_encode($provider_data); ?>,
customerData : <?php echo json_encode($customer_data); ?>,
lexpostData : <?php echo json_encode($lex_post_data); ?>,
csrfToken : <?php echo json_encode($this->security->get_csrf_hash()); ?>
};
console.log(GlobalVariables);
var EALang = <?php echo json_encode($this->lang->language); ?>;
var availableLanguages = <?php echo json_encode($this->config->item('available_languages')); ?>;
$(document).ready(function() {
FrontendBook.initialize(true, GlobalVariables.manageMode);
// GeneralFunctions.centerElementOnPage($('#book-appointment-wizard'));
GeneralFunctions.enableLanguageSelection($('#select-language'));
});
</script>
Ques1: Is this the correct way of accessing the values sent from controller.
Ques2: On console.log(GlobalVariables); I am getting
lexpostData : null
What I am doing wrong.
Please guide
EDIT
SOLVED & CLOSED: I was trying to get differnt name varriable on view. Had to use
lexpostData : <?php echo json_encode($post_data); ?>,
instead of
lexpostData : <?php echo json_encode($lex_post_data); ?>,

In controller you are passing $lex_post_data in post_data
'post_data' => $lex_post_data
So in view instead of
<?php echo json_encode($lex_post_data); ?>
Use
<?php echo json_encode($post_data); ?>

Related

How to Google Tag Manager DataLayer in Wordpress PHP Function

I've been trying to figure out how to make a dataLayer for the Order Confirmation page (Thankyou.php). I wanted to add the following function (via functions.php or Code Snippet) but it gives a fatal error when I try. Can anyone see what I'm doing wrong or if there is a better way to do this?
I'm fairly new but trying to learn and I've been researching but can't find the answer, sorry if this may be a novice question. It gives a fatal error for the < in script so I thought maybe I wasn't supposed to have in PHP but when I remove that then I get a fatal error for unexpected { on same line:
add_action( 'woocommerce_thankyou', 'checkout_datalayer' );
function checkout_datalayer( $order_id ) {
<script>
dataLayer.push({
'ecommerce': {
'currencyCode': '<?php echo $order->get_order_currency(); ?>',
'purchase': {
'actionField':{
'id': '<?php echo $order->get_order_number(); ?>',
'affiliation': 'Website',
'revenue': <?php echo number_format($order->get_total(), 2, ".", ""); ?>,
'shipping': <?php echo number_format($order->calculate_shipping(), 2, ".", ""); ?>,
<?php if($order->get_used_coupons()): ?>
'coupon': '<?php echo implode("-", $order->get_used_coupons()); ?>'
<?php endif; ?>
},
'products': [
<?php
foreach($order->get_items() as $key => $item):
$product = $order->get_product_from_item( $item );
?>
{
'name': '<?php echo $item['name']; ?>',
'id': '<?php echo $product->get_sku(); ?>',
'price': '<?php echo number_format($order->get_line_subtotal($item), 2, ".", ""); ?>',
'brand': 'Brand',
'quantity': <?php echo $item['qty']; ?>
},
<?php endforeach; ?>
]
}
}
});
</script>
}
To anyone interested, I figured out the issue I believe. It was assuming the entire thing was PHP and the only way to stop that was to add ?> before the <script> and <?php after the </script>.

How to Remove Trailing Comma [duplicate]

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 9 months ago.
I am trying to remove the trailing comma from my php statement
<?php foreach( $speaker_posts as $sp ): ?>
{
"#type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
},
<?php endforeach; ?>
Assuming your array is well formed (has indexes starting from zero) you can put it at the beginning, skipping the first record:
<?php foreach( $speaker_posts as $idx => $sp ): ?>
<?php if ($idx) echo ","; ?>
{
"#type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>
Otherwise you need an external counter:
<?php $idx = 0; foreach( $speaker_posts as $sp ): ?>
<?php if ($idx++) echo ","; ?>
{
"#type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>
Since you're apparently outputting JSON, use PHP to do it.
<?php
$json = [];
foreach($speaker_posts as $sp) {
$json[] = [
'#type' => 'person',
'name' => get_field('name_title', $sp->ID),
'sameAs' => post_permalink( $sp->ID ),
];
}
print json_encode($json);
?>
Side note: this will save you from potentially unsafe characters like quotation marks / apostrophes in the field/permalink contents.

How to make auto complete form in cakephp?

I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
// Form and jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
Breaks your JSON structure.
Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
Also, I would create the URL to your datasource in the jQuery setup by
source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)
if ($this->request->is('ajax')) {
condition

Is there a better way of exploding the comma maybe from the last item in the foreach statement?

I have used the Google visulization plugin for displaying charts, because it is dynamically pulled in from a database I have used the following foreach script to display the results:
var chartData = {
dynamic: [
['Date', 'Orders'],
<?php foreach($data['orders-by-date'] as $date => $orderCount): ?>
['<?php echo date('d/m', $date); ?>', <?php echo $orderCount; ?>],
<?php endforeach; ?>
[' ',0] /* Fix for IE8 */
]
};
As you can see I have to add a fix in for IE8 as the last one has to have the comma removed or it breaks in IE8.
Is there a better way of exploding the comma maybe from the last item in the foreach statement? My way works but it adds on a blank value to the end of the chart which isn't ideal.
I hope this makes sense!
I tried the following but doesn't seem to work:
<script type="text/javascript">
var chartData = {
dynamic: [
['Date', 'Orders'],
<?php $fCnt = count($data); ?>
<?php foreach($data['orders-by-date'] as $date => $orderCount): ?>
['<?php echo date('d/m', $date); ?>', <?php echo $orderCount; ?>],
<?php ($date != $fCnt - 1 ? ',' : ''); ?>
<?php endforeach; ?>
]
};
</script>
var chartData = {
dynamic: [
['Date', 'Orders'],
<?php
$last = end($data['orders-by-date']);
foreach($data['orders-by-date'] as $date => $orderCount): ?>
['<?php echo date('d/m', $date); ?>', <?php echo $orderCount; ?>]<?php echo ($date != $last) ? ',' : ''; ?>
<?php endforeach; ?>
]
};
Try this:
var chartData = {
dynamic: [
<?php
$data = array();
$data[0] = ['Date', 'Orders'];
foreach($data['orders-by-date'] as $date => $orderCount)
{
$data[]="[".date('d/m', $date).",".$orderCount."]";
}
echo implode(",",$data);
?>
]
};

JSON error passing html

I have problem with JSON, passing html code, I don't understand because I escaped with addslashes php function.
This is the JSON that fail:
With php JSON is valid:
<?php if(count($articles)): ?>
{"items":[
<?php foreach($articles as $key => $article): ?>
<?php if($key==0 ):?>
{
"foto_g": "<?php echo $article->getRutafoto() ?>",
"foto_th": "<?php echo $article->getRutathumb() ?>"
}
<?php else: ?>
,
{
"foto_g": "<?php echo $article->getRutafoto() ?>",
"foto_th": "<?php echo $article->getRutathumb() ?>"
}
<?php endif ?>
<?php endforeach ?>
],
"nom_coleccio": "<?php echo $coleccio->getNom()?>"
,
"descripcio_coleccio": "<?php echo addslashes($coleccio->getDescripcio(ESC_RAW))?>"
}
<?php endif ?>
And the result that have problem is:
{
"descripcio_coleccio": "<p>El delta de l\'Ebre ha estat l\'escenari d\'inspiració d\'aquesta col·lecció.</p>
<p>La línia de l\'horitzó i el color del paisatge materialitzats en alumini s\'uneixen per a crear volum en forma de joia.</p>"
}
When is the problem?
Thanks Regards
You should use proper encoding functions if possible. In case of JSON you should use json_encode, even if just for particular values.
But it would be easier if you collect the values in an array with associative keys and use json_encode only at the end:
if (count($articles)) {
$items = array();
foreach ($articles as $key => $article) {
$items[] = array(
"foto_g" => $article->getRutafoto(),
"foto_th" => $article->getRutathumb()
}
}
$data = array(
"items" => $items,
"nom_coleccio" => $coleccio->getNom(),
"descripcio_coleccio" => $coleccio->getDescripcio(ESC_RAW)
);
echo json_encode($data);
}
Don't do that! Construct the JSON properly in PHP instead:
<?php
echo json_encode(array
(
"descripcio_coleccio" => $coleccio->getDescripcio(ESC_RAW)
));
?>
Those single quotes shouldn't be escaped:
{
"descripcio_coleccio": "<p>Eldeltadel'Ebrehaestatl'escenarid'inspiraciód'aquestacol·lecció.</p><p>Lalíniadel'horitzóielcolordelpaisatgematerialitzatsenaluminis'uneixenperacrearvolumenformadejoia.</p>"
}

Categories