0

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>';
1
  • It's not same as the other question.. Please see that this one inside an echo statement which is causing problems. Commented Sep 24, 2016 at 22:28

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Didn't work for me. I got this error " Uncaught SyntaxError: Unexpected token <"
var uid="<?php echo $myVariable; ?>"; This line assigning the complete php code not the variable ...
I'll update my answer, I know the problem. Give me a second
You can try it again
1
echo '<script>
$("#dayName").on("change", function(){
// GRABBING THE SELECTED VALUE

var day = $(this).val();
var uid='.$myVariable.'
alert(uid);
alert(day);
</script>';

1 Comment

Thanks.... Your answer worked too..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.