1

I have got this code

/* Popup for hot news */
    $(document).ready(function() {
        var $dialog = $('<div></div>')
            .html('text to be shown')
            .dialog({
                autoOpen: false,
                title: 'Table'
            });

This code is in my JavaScript files which are included by header.php. How to pass PHP output to this function?

Inputing <?php echo($mydata)?> in .html('') above does not solve anything.

Any reason why this gives an error?

Thanks for helping!

2
  • What does $mydata contain? That is essential for giving a proper answer Commented Mar 22, 2011 at 9:40
  • @Pekka: Thanks for your explaination. Commented Mar 22, 2011 at 9:50

2 Answers 2

2

First of all your code is having some problem, $ in php is a prefix of variable and $ in jQuery is a selection sign. You can view the html source(the output) on browser for debug.

I can think of three ways to do so:

(1)The way you have mentioned should work, see the code below

<?php $foo='hi'?>
<script>
alert("<?php echo $foo?>");
</script>

(2)Another way is to separate server side and client slide code clearly for better maintenance

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 
<?php echo"<div id='foo' style='visibility:hidden;'>HI</div>"?>
<script>
alert($('#foo').text());
</script>

(3)The last way is by passing variable from the URL http://example.com/example.php#hi

<script>
var foo= location.href.split('#')[1];
alert(foo);
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Adding <?php //code?> to your JS files do nothing because JS files are not executed by Apache. You can either use Ajax to request for data once your page loads (if the data doesn't need to be there at start) or you can add those PHP code blocks to your HTML code.

Using Ajax (goes in your JS file)

$(document).ready(function(){
   var u = 'data.php';
   var d = {};//data
   $.get(u, d, function(data){
     //got by data. lets invoke some methods here
   });
});

Putting it in your HTML (goes in your HTML file)

var __DATA = '<?php //output some data I prepared earlier ?>'; 
//I'm using __ and capitol case to denote a global variable. Just personal preference
<script src='myjsfile.js' type='text/javascript'></script>
//the variable __DATA is available to your JS file and you can use it

Comments

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.