JSON error passing html - php

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>"
}

Related

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.

Correctly Passing data from Controller to View CodeIgniter

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

Calling an Array As a Value

I do not know if this is possible, but what I am trying to do is create a value for a key within an object that is an array, and then loop through that array in a for loop. My object is coded like this:
<?php $shoots[01] = array(
"name" => "Rustic Farm Shoot",
"id" => "rustic",
"img" => array("img/slider.jpg", "img/testb2.jpg")
); ?>
My code on my page looks like this:
<div id="main-content">
<div class="slideshow">
<?php foreach($shoots as $shootID => $shoot) {
if($_GET["id"] == $shootID) {
for (i = 0; i < $shoot['img'[]].length ; i++) { ?>
<img src="<?php echo $shoot['img'[i]]; ?>" alt="<?php echo $shoot['name']; ?>">
<?php }}}; ?>
</div>
</div>
I have called for the url change earlier on the page, and that is working correctly. I am positive my problem is in this section. This is probably obvious, but I am new to working with PHP, so any help, even if it's something really dumb that I've done, is greatly appreciated.
Looks like you need a nested for-loop.
Here's the rough idea:
$shoots[01] = array(
"name" => "Rustic Farm Shoot",
"id" => "rustic",
"img" => array("img/slider.jpg", "img/testb2.jpg")
);
foreach($shoots as $shootID => $shoot) {
if($_GET["id"] == $shootID) {
foreach($shoot['img'] as $img) {
echo "<img src='$img' alt='$shoot[name]'>";
}
}
}

Cakephp generated form not submitting all data

I have a view called Prices.ctp with the following code. It creates a form which echo's all the data from a variable called $products which contains all the data from a table called Products.
<?php echo $this->Form->create('Product', array('action' => 'changePrice')); ?>
<fieldset>
<h3>Products</h3>
<?php
foreach($products as $k=>$v){
echo $this->Form->hidden('id', array('value'=> $v["Product"]['id']));
echo $this->Form->input('name', array('value' => $v["Product"]["name"] ));
echo $this->Form->hidden('slug', array('value'=>$v["Product"]['slug']));
echo $this->Form->hidden('description', array('value'=>$v["Product"]['description']));
echo $this->Form->hidden('cateID', array('value'=>$v["Product"]['cateID']));
echo $this->Form->input('price', array('value' => $v["Product"]['price']));
echo $this->Form->hidden('photo', array('value'=>$v["Product"]['photo']));
echo $this->Form->hidden('photo_dir', array('value'=>$v["Product"]['photo_dir']));
echo $this->Form->hidden('active', array('value'=>$v["Product"]['active']));
echo $this->Form->hidden('views', array('value'=>$v["Product"]['views']));
echo $this->Form->hidden('created', array('value'=>$v["Product"]['created']));
echo $this->Form->hidden('modified', array('value'=>$v["Product"]['modified']));
}?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
It shoots to this controller method, called changePrice
public function changePrice(){
$this->Product->saveMany($this->request->data['Product']);
$this->Session->setFlash( "Prices Saved.");
$this->redirect ( "/admin/products/" );
return;
}
However when I used debug() to check the contents of of $this->request->data it shows that only the final iteration of the foreach loop in the view is being sent.
To re-word, if the original $products variable (passed into the view prices.ctp) has 4 products: product1, product2, product3, and product4, all with their own data from the Product table (id, name, etc), when the submit button is pressed on the page, only product4's variables will be passed into $this->request->data.
Why is this happening?
Cheers
you can do like this to get the data of all products
<?php
foreach($products as $k=>$v){
echo $this->Form->hidden("Product.{$k}.id", array('value'=> $v["Product"]['id']));
echo $this->Form->input("Product.{$k}.name", array('value' => $v["Product"]["name"] ));
echo $this->Form->hidden("Product.{$k}.slug", array('value'=>$v["Product"]['slug']));
echo $this->Form->hidden("Product.{$k}.description", array('value'=>$v["Product"]['description']));
echo $this->Form->hidden("Product.{$k}.cateID", array('value'=>$v["Product"]['cateID']));
echo $this->Form->input("Product.{$k}.price", array('value' => $v["Product"]['price']));
echo $this->Form->hidden("Product.{$k}.photo", array('value'=>$v["Product"]['photo']));
echo $this->Form->hidden("Product.{$k}.photo_dir", array('value'=>$v["Product"]['photo_dir']));
echo $this->Form->hidden("Product.{$k}.active", array('value'=>$v["Product"]['active']));
echo $this->Form->hidden("Product.{$k}.views", array('value'=>$v["Product"]['views']));
echo $this->Form->hidden("Product.{$k}.created", array('value'=>$v["Product"]['created']));
echo $this->Form->hidden("Product.{$k}.modified", array('value'=>$v["Product"]['modified']));
}
?>

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

Categories