简体   繁体   中英

Pass javascript variable to PHP array using AJAX

I have a variable named var abc=5 and I want to pass that variable via AJAX so each time AJAX runs it I want to store that variable's value in a PHP array variable. Something like this:

$abc=$_request['abc'];
$xyz=array();
array_push($xyz,$abc);

when AJAX runs then I want output something like this:

$xyz[0]=1;
$xyz[1]=2;
.
.
.
.
$xyz[9]=10;

So I can use that array in JPGraph?

Instead of thinking about passing javascript "variables", think about passing modulus data that can be interpreted by Javascript and stored into whatever variables the client side script cares to use.

One easy and popular way to pass data between client and server is to use JSON. The JSON can be created on the PHP side and then sent to the client in response to the request which passes each individual number via Ajax.

It's easy enough to pass numeric data as delimited values, but when you start wanting to pass back and forth more complex data structures, JSON makes the most sense - it closely mirrors the basic data structures of Javascript as well as most modern languages: key/value pairs, arrays (lists of data), true, false, null, modulus strings and numbers.

Your JSON response payload might look like:

"[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]"

You can easily parse it in Javascript like so:

var data = JSON.parse( ajax_response )

See the Fiddle for a mock-up

Don't use multiple AJAX-requests. Just use 1 after you're done. Build the array you want to use in PHP in JSON format .

var string_to_send_with_ajax = JSON.stringify(['1','4','8']);

in php you can then use this in your PHP:

$array = JSON_decode($_POST['string_to_send_with_ajax']);

If you are positive you want to save the variables on the server with PHP, You define an array the first time. Make it a session variable so it will be on the server as long as the browser isn't closed by the user.

$_SESSION['plotArray'] = array();

use array_push to add a value to the array:

array_push( $_SESSION['plotArray'],$_POST['string_to_send_with_ajax']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM