-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.

1
  • What do you want to do with that array? Commented Sep 14, 2016 at 18:20

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

You may want to add that setting header('Content-type: application/json'); will help jquery automatically process the returned data into something javascript can directly consume.
@SuperJer is it required if you add dataType: 'json' to you AJAX call?
@SuperJer, it's not necessary but will edit answer to include your suggestion based on another post

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.