Hi,
I am trying to load pages via ajax. The pages contain an image. When a image field is empty I get a Server error 500 on the AJAX call. . If the image field is filled, it works. I use the following code
<?php
header('Content-type: application/json; charset=utf-8');
$data = [
'title' => $page->title()->value(),
'text' => $page->text()->kirbytext()->value(),
'image' => $page->coverimage()->toFile()->url()
];
echo json_encode($data);
I tried to append the image to the array only if the image exists but it did not work. What is the best way to create the $data
array and add a key, value pair only if it is not empty and ignore it otherwise?
Many thanks
C,
Two options, I think
- Option
$image = $page->coverimage()->toFile();
$data = [
'title' => $page->title()->value(),
'text' => $page->text()->kirbytext()->value(),
'image' => $image? $image->url():null
];
- Option:
$image = $page->coverimage()->toFile();
$data = [
'title' => $page->title()->value(),
'text' => $page->text()->kirbytext()->value(),
];
if($image) {
$data['image'] = $image->url();
}
Ahh beaten to it… i was going to suggest something like this, but @texnixe answer is probably better…
<?php
header('Content-type: application/json; charset=utf-8');
$data = [
'title' => $page->title()->value(),
'text' => $page->text()->kirbytext()->value(),
'image' => function ($page) {
$image = $page->coverimage()->toFile();
if ($image) {
return $image->url();
} else {
// do nothing
}
}
];
echo json_encode($data);
I lifted this from my config for meta tags where i need to do a similar thing… i think the same logic works here.
1 Like
@jimbobrjames That doesn’t make sense. You need to return a string for the image key, not a callable.
Oh. well it seemed to make sense to me, but its 33 degrees despite being 11pm, and my brain has melted.
I recommend some sleep to give the brain some rest.
And then in the morning, while it’s still fresh outside, have a look at what your code above will give you compared to what your desired result should look like.
Both work perfectly. Approach 2 is the solution I am going to use. I use jQueries $.each
for iterating through the JSON elements and building the html. In the first solution I would have a NULL in the array, if the image field was empty in the second it is simply not present so it will not be iterated, which is exactly what I was looking for.
In regards of solution 1 - I was not aware that I can use an expression in the array, still learning PHP, good to know!
Many thanks!