HEYHEY
HEYHEY

Reputation: 533

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?

Upvotes: 2

Views: 93

Answers (3)

Adam Copley
Adam Copley

Reputation: 1495

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";

Upvotes: 4

Danny Nadeau
Danny Nadeau

Reputation: 115

If you only need the array for the current user and you don't need to persist the data longer that the user session.You could use a session variable for that.

$_SESSION['names'][] = $_POST['names'];

Like other user have said, don't forget to add session_start() somewhere in the beginning of your code.

Edit: I updated my answer with Adam Copley comment

Upvotes: 3

Matt
Matt

Reputation: 5428

Yes, you can add items to array the way you are doing it or using push but keep in mind that PHP is not persistent, so if you are talking about an ajax call only the values you added during that call are going to exist.

<?php 

$names = array();
$names[] = "Mark";
$names[] = "Franklin";
$names[] = "Sam";

var_dump($names);

Output:

array(3) {
  [0]=>
  string(4) "Mark"
  [1]=>
  string(8) "Franklin"
  [2]=>
  string(3) "Sam"
}

If you want persistence, you're going to have to store the values in a cookie, db, filesystem, memory cache like redis, or some other place.

Upvotes: 2

Related Questions