简体   繁体   中英

How to access the value of variable `a` in first php script to second php script and linked by ajax call

Example: my code in first php script:

<?php
$a = array('green','yello','blue');

Then in my second script:

<?php
echo $a; //display the value based on my first script

jQuery-AJAX links the two scripts

PURPOSE:

I have navigation bar in my web page that has 3 menu/option. Once i click one of the menu, i'll send it's index to the second script using this code $(this).closest('li').index() (which works correctly). then the second script will check the value of the index being sent....the index will serve as the key of the array...

PROBLEM:

Can't get the value (array) of $a in my second script

NOTE:

Can't I use only one script since i want to catgorize the scripts.....this is only small part of my project

The PHP variables are available always only within one request. New request means new scope and the variables set up in the previous script were forgotten. To keep a value across multiple requests, you may use for example session.

Solution with sessions

Script 1

session_start();
$_SESSION['a'] = array('green','yello','blue');

Script 2

session_start();
$a = array('green','yello','blue');

Solution with require()

The other option would be to include the script 1 where the array is declared and initialized to the script 2 (and to all other script where you need the array).

Script 1

$a = array();

Script 2

require('script1.php');
$b = $a; // feel free to use the array $a here

Solution with passing the array to the client and back

Yet another solution (even though most likely not a good one) would be to use json_encode($a) to encode the array as a json, send it to the client and then in the ajax request send the array back to the server to the script 2. Script 2 would parse the json using json_decode().

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