0

I want to insert js variable into my php function in javascript.

JS:

function moderator_activity(who){
 var getIt = <?php echo json_encode(moderatorActivity()); ?>;
}

I want to make something like that:

var getIt = <?php echo json_encode(moderatorActivity(who)); ?>;

where "who" is js variable.

I tried to do:

var getIt = <?php echo json_encode(moderatorActivity(?>who<?)); ?>;

but i got:

Parse error: syntax error, unexpected ';', expecting ')'

I don't want to make another file with php function so that's why i combined it :)

I hope you understand.

3
  • php and javascript run in different environments at different times. What you are trying can't be done. Explain your use case Commented Jul 20, 2014 at 2:06
  • That is just not possible. JS runs on the browser, PHP on the server side. Commented Jul 20, 2014 at 2:06
  • @charlietfl I'm getting value from mysql which I want to show in html. I has got event in pagination <a onclick="moderator_activity('<? echo $row['name']; ?>');">Next</a> Commented Jul 20, 2014 at 2:10

1 Answer 1

1

Say you create a file named script.php, use can use PHP to change the MIME of the document, using the header PHP function.

<?php header("Content-Type: text/javascript"); ?>

window.onload=function(){
  console.log('<?php echo "Using PHP!"; ?>');
}

Although this data isn't interchangeable because it's generated server-side, this is the best you're going to get.

You would include it on you website, something like:

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

As a better alternative, you could try something with Ajax.

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

2 Comments

I tried with json and I guess it's the best way to do what I want, but thanks for your reply.
Alright, you should accept the answer anyways because it solves the question regarding the post. Thanks.

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.