Getting weird "undefined" on API call

Setting up a simple API per the cookbook and I’m getting a weird result:

Here’s my API code:


header('Content-type: application/json; charset=utf-8');

$data = $pages->find('podcasts')->children()->visible()->limit(5);

$json = array();

foreach($data as $entry) {

  $json[] = array(
'url'   => (string)$entry->url(),
'title' => (string)$entry->title(),
'date'  => (string)$entry->date('F d, Y'),
'subtitle'  => (string)$entry->subtitle(),
		'audio'  => (string)$entry->file(),


echo json_encode($json);


And the API call:

// call our api
$.getJSON('http://localhost:8888/admin/api', function(r) {
	// loop through the result
	$.each(r, function(i, entry) {
		var episode;

		episode += '<div class="player">';
			episode += '<a href="javascript:;" class="play-button"><i class="fa fa-play-circle"></i></a>';
			episode += '<a href="javascript:;" data-audio='+ entry['audio'] +'><h4 class="nomargin">'+ entry['title'] +'</h4></a>';
			episode += '<p class="nomargin">'+ entry['date'] +'</p>';
			episode += '<p class="mar-t0"><strong>'+ entry['subtitle'] +'</strong></p>';
		episode += '</div>';




Hmm… I’d think that if it was a problem with the code you’ve provided, then you would at least have the play icon on your “undefined” entry since for that the entire episode variable would have to be undefind. So, I’m suspecting that the bug is not in the code you posted.

Do you get any JavaScript console errors? Can you inspect the DOM with your browser tools? What does the markup before / after the ‘undefined’ look like? What does the template that contains the #player look like?

No console errors.
Shows up before each .player div

Ah, you have an “undefined” before each .player element. Now I see it: You have to initialize the episode variable as an empty string

var episode = '';

Otherwise the first += will append to an undefined variable.

(JavaScript type conversion bullshit converts the variable value undefined to a string before appending the other string which means the first += actually does episode = 'undefined' + '<div class="player">'

Ahh, makes sense. Thanks! :+1: