1

I have a php function which I am using to calculate statistics of information in a database. I want to output the results in a string and pass it to JQuery to be able to make graphical representations of the data.

Is it possible to pass a string from PHP into a JQuery method in this way?

Thanks in advance

mickzer
  • 5,958
  • 5
  • 34
  • 57
  • Potential duplicate of "[passing search parameter through jquery](http://stackoverflow.com/q/3339731/2432317)" and/or "[passing data from javascript to php using Jquery](http://stackoverflow.com/q/4011160/2432317)". – e-sushi Jul 28 '13 at 12:25

3 Answers3

1

Jquery is javascript was executed by browser.

Set the header as javascript on your php and load with script tag.

<script type="text/javascript" src="/yourphpfile.php"></script

And then in file yourphpfile.php

<?php
    header('Content-type:application/javascript');
    $stringFromDb = functionGetContentFromDB();
?>
var data = "<?= $stringFromDb ?>";

List item

emaniacs
  • 137
  • 4
0
    <?php
    $var = "somestring";

    echo '<script>var str = "'.$var.'";</script>';
    ?>

you can do that this way

UnknownError1337
  • 1,222
  • 1
  • 12
  • 16
0

There are two ways, you can output this into the javascript onload, echoing to the inline javascript.

<script>
    var string = "<?php echo $string; ?>";
</script>

Alternatively you can fetch the data from ajax using json_encode in php to get the data in the correct format.

If you then use getJson (http://api.jquery.com/jQuery.getJSON/) you will have the data in the correct format.

Marcus Hughes
  • 5,123
  • 1
  • 25
  • 39