0

I'm using this code to bring a php var into a js function but I can't seem to get the proper formatting (output). I think highcharts needs numbers but it is creating a string even if I use "intval".

series: [{
            name: 'Spyware',
            data: [0, 3, 0, 0, 0]
        }, {
            name: 'Viruses',
            data: [ <?php echo json_encode(intval($virusNum)); ?> , 0, 0, 0, 0] 
        }, {
            name: 'Brute Force Attacks',
            data: [0, 0, 0, 0, 0]
        }, {
            name: 'Host Sweeps',
            data: [0, 0, 0, 0, 0]
        }, {
            name: 'Anonymizer/Proxy Server',
            data: [0, 0, 0, 0, 0]
        }]

Here's where I create the $virusNum variable.

$viruses[$aPos] = intval($freq);
$virusNum = $virusNum + $viruses[$aPos];
2
  • why do you use the json_encode function? Commented Jul 6, 2016 at 21:47
  • JSON is always string, you need to JSON.parse the json_encodeed result. Commented Jul 6, 2016 at 21:49

2 Answers 2

1

I think you may need to use the $options parameter of the json_encode function in PHP:

json_encode(intval($virusNum), JSON_NUMERIC_CHECK)

JSON_NUMERIC_CHECK (integer)

Encodes numeric strings as numbers. Available since PHP 5.3.3.

Sign up to request clarification or add additional context in comments.

1 Comment

What does the code look like after PHP has processed it? Does $virusNum start with a value of 0?
0

Why json-encode there? This is just an integer value, so there is no need for that.

data: [ <?php echo intval($virusNum); ?> , 0, 0, 0, 0] 

9 Comments

good habit to get into, if nothing else. kind of like writing secure sql queries, even if you know there's no possibility of an injection problem.
@MarcB I suppose. But I think relying on non-standard, library-specific JSON encoding behaviors, such as how primitives are encoded/decoded when they are not within an appropriate data structure (object or array) - something not covered by the JSON specification - is just as bad.
This doesn't work either. - Wanted to add this as I just saw the 2 comments appear after saving this comment that I'm a php noob so those comments are greek to me. Thx anyway.
@RandyMCode what does var_dump($virusNum) produce? Also, this code you show that produces the javascript output is being served up by a PHP page right (i.e. this isn't in some javascript include somewhere)?
var_dump($virusNum) gives: C:\MAMP\...\threatcharts_datafeed_2016-07-08a.php:71:int 141 - All I need is the 141. I put the "..." in the output, the result was the path to my php file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.