user3419087 user3419087 - 6 months ago 12
Javascript Question

echo in jquery doens't output as expected

I found on stackoverflow how to use a php variable in jquery, but on my test page, it simply isn't working:

$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});


The code above outputs "" literally in the box where I want it to say "test123". I tried using single quotes instead of double, other small changes ... Didn't get it to work. Am I missing something?

The code above sits in a .js file which is linked in a .php page, which is (again) linked in my index.php file via require_once.

Answer

You should not use PHP in javascript files (.js). Javascript and PHP are different languages. PHP works on the server-side and Javascript on the client-side.

You have to put this code in your <head> under the jquery.js file, like this:

<script type="text/javascript" src="link-to-jquery-file.js"></script>
<script type="text/javascript">
$('#q').keyup(function(e) {
    var test = "<?php echo 'test123'; ?>";
    alert(test);
});
</script>

Also make sure your file extension ends with .php

There is also an advanced solution for this, and that would be using the header() function. Save as javascript.php or someting Example:

<?php
header("Content-Type: text/javascript");
?>
$('#q').keyup(function(e) {
    var test = "<?php echo 'test123'; ?>";
    alert(test);
});

Then attach the file in your <head> like this:

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

Goodluck!