Browse array from ajax function

0

Good, I have a variable session called api where I have two words stored

echo $_SESSION["api"]['0']; This would be parabra1 echo $_SESSION["api"]['0']; This would be word 2

This variable is in a php file and is returned to an ajax function in success: function(data){

From the php file I do echo $_SESSION["api"];

When I go through data with a for, what I need is for you to show me the two words: word1 and word 2, and the result I get is 'p''a''l''a' etc ..

for(var i = 0; i < data.length; i++){
            alert(data[i])
    }

What am I doing wrong? Thank you very much.

    
asked by Lorenzo Martín 23.09.2017 в 22:58
source

1 answer

0

You have to return each index from where you save the words separately as an array and then convert it to json and return it:

$arr = array();
$arr[0] = $_SESSION["api"];

echo json_encode($arr);

And now if you can get the full word:

//..
.success(function(data){
  for(var i = 0; i < data.length; i++){
       alert(data[i])
    }
})

And actually I do not know if it's a graphic type error but you're saving both the value of word1 and word2 in the same key api $_SESSESION["api"] . You should assign a different key for both words:

$_SESSION["api1"] = "palabra1";
$_SESSION["api2"] = "palabra2";

$arr = array();
$arr[0] = $_SESSION["api1"];
$arr[1] = $_SESSION["api2"];

echo json_encode($arr);
    
answered by 23.09.2017 / 23:27
source