lukescomputers
lukescomputers

Reputation: 57

Sending PHP Strings Variables to a Javascript String Variables

Hi I am trying to send a long string of numbers from a file to Javascript. One I get it in Javascript as a string the rest will be easy.

This is the PHP code that grabs the series of numbers. It does grab them properly because it prints it out perfectly if I instruct it to do so.

$data = readfile($dataFile);

This is the Javascript Code:

var data = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

When ever I run it the variable "data" is set to a random number. I assume it is the the number of characters in the sequence. I am relatively new to PHP and Javascript so a nice and clear explanation would be greatly appreciated. Thanks in advance.

Upvotes: 0

Views: 43

Answers (3)

Claudio Venturini
Claudio Venturini

Reputation: 698

The number that is set in the variable $data is the number of bytes read by readfile. This is because readfile only reads the file and outputs its content to the standard output. To get the actual data in the file and assign it to a viariable, you can use file_get_contents(), like this:

$data = file_get_contents($dataFile);

Then the javascript assignment is good ;)

Upvotes: 1

Michael Wagner
Michael Wagner

Reputation: 1038

Readfile reads the contents of the file and outputs them. It returns the byte length of the file, so $data is the number of the read bytes. link.

Upvotes: 3

Paul
Paul

Reputation: 141839

You need quotes if you want it to be a string in Javascript:

var data = '<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;';

Upvotes: 0

Related Questions