Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Javascript Array -> PHP

Let's say I have a javascript array with a bunch of elements (anywhere from 50-200).

I want to send that to PHP (prepared statement) using ajax. Currently, I .load a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.

array[i] = variable;

like image 491
switz Avatar asked Feb 17 '11 22:02

switz


People also ask

How to use PHP array in JavaScript function?

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function. PHP array can be converted to JavScript array and accessible in JavaScript. Whatever the array type is, a single or multidimensional or indexed or associative array.

Can you pass an array in JavaScript?

Use the apply() Method to Pass an Array to a Function in JavaScript. In the example given above, we have an array of names and a function named displayName() to print all elements of the names array. We use apply() method to pass an array to displayName() function.


1 Answers

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.

like image 76
Gareth Avatar answered Sep 21 '22 21:09

Gareth