Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
krx Avatar asked Jan 06 '10 14:01

krx


People also ask

How to pass Array to PHP using AJAX?

on('submit', function (e) { e. preventDefault(); var data = $(this). serializeArray(); var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose for (i = 0; i < myvals. length; i++) { data.

How to pass an Array from JS to PHP?

You could use JSON. stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it. don't forget to sanitize your inputs, or you're toast! :D.

What is Array in AJAX?

An Array is used to store multiple values in a single variable. This can be used to pass the group of related values as data to the $. ajax for processing and get the response. E.g. pass all checked checkboxes values, selected values from the list.


2 Answers

data: { activitiesArray: activities }, 

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

<?php $myArray = $_REQUEST['activitiesArray']; ?> 
like image 145
Valentin Golev Avatar answered Sep 24 '22 05:09

Valentin Golev


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.

like image 38
jvenema Avatar answered Sep 25 '22 05:09

jvenema