1,105,534 Community Members

passing a php variable to java

Member Avatar
GraficRegret
Junior Poster
182 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

is there any way to pass a variable from php into a variable in javascript? or do I need to revert to AJAX to get this done?

Member Avatar
diafol
Where are my eyes?
12,977 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,848 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
0
 

I'm assuming you mean javascript and not java. No need for ajax. Something as simple as this:

<script>
var myVar = '<?php echo $myvar;?>';
//rest of code
</script>
Member Avatar
GraficRegret
Junior Poster
182 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

That's just about what I thought it would be, is there anything different I need to do if I need it passed into a function?

Member Avatar
diafol
Where are my eyes?
12,977 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,848 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
0
 

Exactly the same:

function myFunc('<?php echo $myvar;?>'){
   var secondVar = '<?php echo $myvar2;?>';
}

However, I assume that a js variable would be passed to the function as a parameter, so it would be best to apply the php value to the var instead.

What you can't do is evaluate js vars with php in the middle of a script - for that you would need ajax.

Another side note: you may need to force data typing on js vars, such as parseInt(), as errors can often occur without an obvious cause.

Member Avatar
GraficRegret
Junior Poster
182 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

Ok, thanks again D

Member Avatar
GraficRegret
Junior Poster
182 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

is it posible to put information from a database into an array in javascript?

Question Answered as of 1 Year Ago by diafol
Member Avatar
diafol
Where are my eyes?
12,977 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,848 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
0
 

Of course. I usually find passing data to js easier via json as it saves a lot of hassle with looping and all that nonsense.

For example:

while($data = mysql_fetch_assoc($result)){
    $dbdata[] = $data;
}
$json = json_encode($dbdata);


<!--later on-->

<script>
var myJson = <?php echo $json;?>; 
</script>
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article