-1

Possible Duplicate:
javascript array converted to a php array?

I have an array in javascript, Now i need to assign javascript array to php array
i am beginner to scripting language,

Can anyone please help me
Thanks in advance.

<script type = text/javascript >
var jsArray = [];
var jsDescArray =   [];
 for (var i = 0; i <= <?php echo $t_num ?>; i++) {
     jsArray.push( "<?php echo $url ?>="+thread[i].id  );
     jsDescArray.push( thread[i].title );
}
<?php
$str=json_decode('jsArray'); 
$str1[] = json_decode( 'jsDescArray', true );
?>
</script>
Community
  • 1
  • 1
Giri
  • 507
  • 6
  • 23
  • PHP runs on the server, JavaScript is on the client. You need to send the array to a PHP (using AJAX is one way). – gen_Eric Aug 08 '12 at 14:39
  • Try writing a separate php file that can accept the data and use it. Then write javascript that will send the data to that new php file by AJAX. – ColBeseder Aug 08 '12 at 14:46
  • Hi Giri you didn't declar the javascript var "thread, id,title" . missing semicolon in "echo $t_num;" and "echo $url ;" in your code.. – Luke Nov 18 '17 at 12:08

3 Answers3

4

First off, Javascript is evaluated on the client-side, long after the PHP code has been scanned and dealt with on the server-side. Thus, this type of code simply cannot work.

Secondly, there's really no reason for this. Because you are filling an array in Javascript prior to assignment, you should really just pass the variables ($url) directly into $str and $str1[]. If this is something that must be dealt with on the client-side, call and retrieve data from a .php file with AJAX to transfer your Javascript arrays over.

Reference: https://developer.mozilla.org/en-US/docs/AJAX

Daniel Li
  • 14,976
  • 6
  • 43
  • 60
1

PHP is run on the server, and the result is sent to the browser. Only then can the JavaScript be run.

To send stuff from JavaScript back to the server, you need to use AJAX or similar. You might want to reconsider your approach to problem-solving, but it really depends on the context of what you are trying to do here.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thanks for replay my requirement getting latest forum(vbulliten) details/threads. Here my approach is :- creating 2 arrays (This array available in current php file ) i need these 2 arrays in another php file. please give me a good approach – Giri Aug 08 '12 at 16:27
0

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

see url

Pass Javascript Array -> PHP

Community
  • 1
  • 1
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53