Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I know I am doing this totally wrong and haven't got an idea how to do this.. basically I have a javascript function and trying to use php to declare as array all teams if round equals to 1. The teams and round will come from the parameters in function teamElement()

  function teamElement(round, team, isReady) {

  <?php if(round == 1)  $round2_array[] = team) ?>

  document.write('<p>round: ' + round + '<br>team ' + team.name + '<br> is ready ' + isReady);

...

Anyone can help with this please?

many thanks.

share|improve this question
You cannot use Javascript variable 'team' inside PHP code. <?php if(round == 1) $round2_array[] = team) ?> – balajimca Aug 10 at 11:00
You are going to have to use AJAX for that. – putvande Aug 10 at 11:03

marked as duplicate by Juhana, Dagon, deceze, Sven, Sindre Sorhus Aug 10 at 15:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

Taking a look at your code, specifically this part:

function teamElement(round, team, isReady) {
  <?php if(round == 1)  $round2_array[] = team) ?>

I see you lack of some basic knowledge: Javascript is a client side scripting language, while PHP is a server side scripting language. PHP and Javascript are executed in two very different moments (generally PHP first and then Javascript (without using AJAX)). Therefore they cannot share variables that easily.

There are ways, though, to connect the two of them:

To pass a PHP variable to a Javascript script you could simply use string interpolation or the templating features of PHP:

var x = <?php echo $x; ?>;

Just notice that that is considered very bad practice and you should use AJAX here as well.

To pass a Javascript variable to a PHP script you can use AJAX (Asynchronous Javascript And XML), to execute a PHP script "in the background", after the page is loaded. In this regard I suggest you to take a look at the nice jQuery library which provides a very helpful set of functions for this task.

share|improve this answer
Thanks for the help, in this case is there anyway I use SQL statement to insert the teams from the team parameter in the teamElement function if that makes sense? – Karim Ali Aug 10 at 13:00
@KarimAli, assuming you are executing the query from PHP, yes you can: with AJAX. – Jeffrey Aug 10 at 15:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.