Passing JavaScript array to PHP through jQuery $.ajax
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?
Solution 1:
data: { activitiesArray: activities },
That's it! Now you can access it in PHP:
<?php $myArray = $_REQUEST['activitiesArray']; ?>
Solution 2:
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.
Solution 3:
You need to turn this into a string. You can do this using the stringify method in the JSON2 library.
http://www.json.org/
http://www.json.org/js.html
The code would look something like:
var myJSONText = JSON.stringify(myObject);
So
['Location Zero', 'Location One', 'Location Two'];
Will become:
"['Location Zero', 'Location One', 'Location Two']"
You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.
Data can be returned from the server in a similar way. I.e. you can turn it back into an object.
var myObject = JSON.parse(myJSONString);