Page 1 of 1

How can i assign a javascript variable to php variable

Posted: Tue Jan 06, 2009 1:21 am
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......

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

Posted: Tue Jan 06, 2009 6:12 am
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.

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

Posted: Tue Jan 06, 2009 6:42 am
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 ;)

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

Posted: Wed Jan 07, 2009 6:27 am
by maartha
Thank you friends..

But is there any other method other than query string?

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

Posted: Wed Jan 07, 2009 6:40 am
by nvartolomei
read about ajax