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>
-
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– gen_Eric2012年08月08日 14:39:39 +00:00Commented Aug 8, 2012 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– ColBeseder2012年08月08日 14:46:49 +00:00Commented Aug 8, 2012 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– Luke2017年11月18日 12:08:19 +00:00Commented Nov 18, 2017 at 12:08
3 Answers 3
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.
Comments
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.
1 Comment
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