-1

I am sending an array I have in javascript to php using:

usernames = ['username1','username2']


$.ajax({
            url: "my_Url",
            type: "post",
            data: {username:usernames} ,
            success: function (response) {
               // you will get response from your php page (what you echo or print)     
               alert(response);
            }
        });

data will be sent to the php script containing what is below:

<?php
header('Access-Control-Allow-Origin: *');
$usernames = $_POST['username'];
echo $usernames;
?>

The problem is I get an alert saying Array but not what is in the actual array itself. How do I get what is inside the array and put it in a variable again.

odai
  • 190
  • 1
  • 5
  • 19
charles M
  • 75
  • 1
  • 7

1 Answers1

0

Because the data type is an array, that is what javascript will alert from the echoed PHP. Typically, you can convert the array to a string, which can be visualized in the ajax response, using json_encode()

echo json_encode($usernames);

and then to process the JSON on the frontend, use JSON.parse(). As one user has pointed out, it is useful in the backend script to set a content header before echoing the json:

header('Content-Type: application/json');

This approach is discussed in more detail here.

Another possibility that is useful for a numeric array such as in your code, is to simply echo the imploded array, which will convert it to a string:

echo implode(",", $usernames); // the ajax response will be username1,username2 here
Community
  • 1
  • 1