Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php, adding ajax passed values to a variable

So, in js, you can have a variable outside of a function which push can be used to add values to it and access it anywhere else.

var names = [];
function my_function_js(){
    alert(names);
}

In php, can a variable act in the similar manner?

For example, let say I have an ajax function with a variable. Then I want to know if I can add different values to this variable using ajax at multiple occasions.

$names   = array();
function my_function(){
   $names[]   = $_POST['names'];
}

Let say, for the first ajax call, mike was passed. Then steve for second call and sean for the last.

Would each value override the previous value or would it be saved like in js?

(In other words, I would like to know if I can add values to a php variable using ajax multiple calls).

Thanks.

EDIT:

It was pointed out that ajax variable (in this case $names) will be reset every time a new ajax call is made.

Then, how about have another variable that does not get affected by the ajax call and simply push the ajax value to it?

For example:

$FULL_NAMES   = array();
function my_function(){
   $names  = $_POST['names'];
   $FULL_NAMES[]   = $names;
}

Would something like this work?

like image 465
HEYHEY Avatar asked Jun 23 '26 16:06

HEYHEY


1 Answers

There is the option of storing the value in the $_SESSION array.

You would need to add

session_start();

to the top the page

and use.

$_SESSION['varname'][] = "whateveryouwant";
like image 173
Adam Copley Avatar answered Jun 26 '26 06:06

Adam Copley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!