Php : How To Pass Database Value Into A Javascript/jquery Function
I am implementing tags feature in my project. In my demo tags i found they are passing names in a javascript function for the autocomple. This is a function in my demo project,
Solution 1:
You could echo the variable onto the page using PHP's json_encode
. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:
<script>
$(function() {
var sampleTags = <?phpecho json_encode($query); ?>;
})();
</script>
But a better way would be to request these values via Ajax. Say you have a PHP script named values.php
:
<?php#...#assign $query here#...echo json_encode($query);
Then, in JavaScript (on the page where you want to use the sampleTags
variable), you can use jQuery's .ajax
function to make an easy Ajax request:
<script>var sampleTags;
$.ajax({
url: 'values.php'
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
</script>
I haven't tested this example. Obviously you'll want to tweak it to fit your environment.
Solution 2:
You will have to write an ajax function for this
$.ajax(
url : "<?phpecho site_url('controller/method')?>",
type : 'POST',
data : 'para=1',
success : function(data)
{
if(data){
var sampleTags = data;
}
}
);
Solution 3:
Just echo your php variable
$(function()
{
var sampleTags = '<?phpecho$data["query"]; ?>'
Post a Comment for "Php : How To Pass Database Value Into A Javascript/jquery Function"