Hkm Sadek Hossain Hkm Sadek Hossain - 2 months ago 8
Javascript Question

How to assign a php variable inside echoed js code?

I have js code which is inside echo statement (which is retried using ajax call).
I need to send another ajax request based on the first result. So I need to assign a php variable inside a js variable (php variable is retrieved from database during first ajax call)

echo '<script>
echo '<script>// SEINDINGM REQUEST FOR SELECTED DAY
$("#dayName").on("change", function(){
// GRABBING THE SELECTED VALUE

var day = $(this).val();
var uid=//Here I want to assign the php variable //;
alert(uid);
alert(day);
</script>';

Answer

replace

var uid=//Here I want to assign the php variable //; 

with

var uid='.$myVariable.';

PHP doesn't care if this value will end up in JavaScript code. It just writes the content wherever you want it to be. The document will arrive at the client as usual HTML including the already inserted variable content. Then it will be normally executed by JavaScript.

If the variable's content is a String then you have to write it like:

var uid="'.$myVariable.'";

Here are more information and different options how to include variable content within echo php - insert a variable in an echo string