Passing JavaScript array to PHP through jQuery $.ajax


Question

I want to manipulate a JavaScript array in PHP. Is it possible to do something like this?

$.ajax({
       type: "POST",
       url: "tourFinderFunctions.php",
       data: "activitiesArray="+activities,
       success: function() {
            $("#lengthQuestion").fadeOut('slow');
       }
    });

Activities is a single dimensional array like:

var activities = ['Location Zero', 'Location One', 'Location Two'];

The script does not complete when I try this... How can I fix it?

1
77
5/18/2017 4:03:52 PM

Accepted Answer

data: { activitiesArray: activities },

That's it! Now you can access it in PHP:

<?php $myArray = $_REQUEST['activitiesArray']; ?>
145
10/19/2017 5:46:57 AM

You'll want to encode your array as JSON before sending it, or you'll just get some junk on the other end.

Since all you're sending is the array, you can just do:

data: { activities: activities }

which will automatically convert the array for you.

See here for details.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon