0

How can I pass the php variables into an external javascript file? I found a lot of questions regarding this but I can't figure it out anyhow.

In the HTML file I have this link

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

This is the myscript.php file that I have been trying to output as a javascript file:

<?
Header("content-type: text/javascript");
?>

$(document).ready(function() {

$("#validate_form").validate({
    rules: {
        page_title: "required",
        seo_url: "required"
    },

    messages: {
        page_title: "<?=$page_title?>",
        seo_url: "<?=$seo_url?>"
    }
 }); 
});
Michael
  • 3,982
  • 4
  • 30
  • 46
perqedelius
  • 105
  • 1
  • 1
  • 10

1 Answers1

2

Append them using a query string:

<script type="text/javascript" src="myscript.php?page_title=whatever&seo_url=whatever"></script>

<?
Header("content-type: text/javascript");
?>

$(document).ready(function() {

$("#validate_form").validate({
    rules: {
        page_title: "required",
        seo_url: "required"
    },

    messages: {
        page_title: "<?=$_GET['page_title'];?>",
        seo_url: "<?=$_GET['seo_url'];?>"
    }
 }); 
});
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 2
    You might want to do some escaping before you insert those `$_GET` values in the JavaScript code though. `json_encode` should do. – Mattias Buelens Feb 13 '13 at 23:54
  • This is just a part of the javascript and I think it's a total of 20 different php variables in script. Is there another way, like making the variable global or something? – perqedelius Feb 13 '13 at 23:56
  • You can also have the PHP file include another file with variables in them. Al of the regular rules of PHP apply. – John Conde Feb 13 '13 at 23:57
  • +1 to using `json_encode`. Especially if using query-string parameters (since that's user-input). This method wouldn't properly escape. – Colin M Feb 14 '13 at 00:07
  • It worked to include a php file with variables. I'm not good at javascript so I don't know how to use json_encode. Can someone right a simple example code? – perqedelius Feb 14 '13 at 00:50