Accessing a php variable via javascript

I am setting a php variable to the value of a query string value

i.e



<?php

	$name= $_GET["username"];

?>


Now I have a button on the page that needs to call a function that uses this $name value

i.e



<input class="noprint" name="Save" value="Save Certificate as PDF" onClick="javascript:saveCertificate();" type="button">


My javascript function is as follows:



<script language="JavaScript" type="text/javascript">

function saveCertificate() {

	alert("Hello World!");	

  	jsvar = <?php echo $name; ?>;

	alert("name = " + jsvar);	

}
</script>


I am getting my “Hello World!” message displayed but it is not displaying the "name = " string.

Any ideas what I am doing wrong here?

Thanks

Paul

Might be just a typo Paul. Note quotes around string var.


<script language="JavaScript" type="text/javascript">

function saveCertificate() {

    alert("Hello World!");    

      jsvar = "<?php echo $name; ?>";

    alert("name = " + jsvar);    

}
</script>

Brilliant! Thanks Anthony - that was the problem. I thought I was doing something completely wrong as combining javascript and php always gets me confused:)

You might want to escape the string, just in case. You can do that easily with json_encode().

In the future, first, get the javascript working by itself. If this means hardcoding certain values, fine.

Once you have that done, then, you can worry about using php to dynamically create the value. The benefit here is, your goal with php is reduced to “make php generate some text that looks just like the working javascript”.

You would have noticed right away that the working javascript


jsvar = "fred";

Is different than


jsvar = fred;

Same goes for sql, and many other things.

The best advice for the newbies I’ve ever seen.