Pass a php string into JQuery

Solution: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 ?>";

Solution:2

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.