How can i assign a javascript variable to php variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
maartha
Forum Newbie
Posts: 4
Joined: Wed Sep 17, 2008 2:07 am

How can i assign a javascript variable to php variable

Post by maartha »

hello everybody

I need to assign the value of js variable to php variable when js for loop works...my code look like this

<script langauge="javascript" type="text/javascript">
/* there is an array with values let it be */
var dataArray = array("1","2","3")
for(i = 0;i < dataArray.length;i++)
{
/* Here i need to assign the js variable to php variable so that i can use it in a query. I tried the following script*/
<?php $i = ?> dataArray

<?php
$query = "SELECT * FROM tablename WHERE field = '$i'";
//code continues....
?>
</script>
But i am getting error.... :cry:

Please help me to find out the solution....please......
silenceghost
Forum Newbie
Posts: 22
Joined: Sun Oct 19, 2008 3:25 am

Re: How can i assign a javascript variable to php variable

Post by silenceghost »

We cannot assign javascript variable to php directly because php works on server side and javascript works on client side so there is a different process running on but we can assain php variable to javascript
var i='<?=$i?>'
--We can use ajax instead to assign javascript variable to php but it's very confusing to use.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: How can i assign a javascript variable to php variable

Post by VladSun »

:o :lol:

[js]var js2php = 'value to set in PHP (in $_SESSION obviously)';var img = new Image();img.onload = function () {    alert('ok');    }; img.src = 'index.php?myjsvar=' + js2php;[/js]

No AJAX needed ;)
There are 10 types of people in this world, those who understand binary and those who don't
maartha
Forum Newbie
Posts: 4
Joined: Wed Sep 17, 2008 2:07 am

Re: How can i assign a javascript variable to php variable

Post by maartha »

Thank you friends..

But is there any other method other than query string?
nvartolomei
Forum Newbie
Posts: 11
Joined: Tue Jan 06, 2009 3:46 pm

Re: How can i assign a javascript variable to php variable

Post by nvartolomei »

read about ajax
Post Reply