Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm just learning php, and I am trying to parse some files I have, and then send the information to javascript. This is my php:

$datesArray = readFile();
echo json_encode($datesArray);

This echoes:

["120102000000","120102000500","120102001000","120102001500","120102002000","120102002500","120102003000"]

Which is what I want. However, my javascript, which looks like this:

var dates = <?php echo json_encode($datesArray); ?>;
console.log(dates);

keeps giving dates back as null, and I am not sure why. I have tried encoding the array as utf-8, and I have tried using jQuery.parseJSON which also did not work.

Thanks--

share|improve this question
    
Not that I expect it to change much, but try <?= json_encode($datesArray ?>; –  Seiyria May 5 at 17:46
    
@Seiyria I'm sorry I'm not familiar with that syntax, do you mean like this: var dates <?= json_encode($datesArray) ?>; ? I keep getting a syntax error back :/ –  user3605205 May 5 at 17:56
    
When you look at the source code with the JS output, what you see? Can you see what if being echoed by php? –  lsouza May 5 at 18:04
    
@Isouza Okay, I see, I'm getting var dates = ;. How do I tell Javascript how to interpret the <?php ?> tags? –  user3605205 May 5 at 18:15
    
wait... what kind of server are you running on? –  Nick J May 5 at 18:39
add comment

1 Answer 1

Just checking, but is that JavaScript with PHP in a .js file? By default, Apache only runs PHP in files ending in .php so that would mean your PHP is getting parsed as plain text by the server.

If that is the case, the easiest solution is to run that part of the script in some <script> tags.

Alternatively you could make Apache try to serve .js files as PHP file via Mime-Types; but that is really a mess not worth implementing.

share|improve this answer
    
This is all in a .php file. The full block loks like <script> var dates = <?php echo json_encode($datesArray) ?>; console.log(dates);</script> –  user3605205 May 5 at 18:16
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.