lundi 2 février 2015

Passing "unlimited" values through ajax


I'm trying to make a filter for google maps api on our site so people can choose to display information only related to locations that are checked. I'm not sure the best way to pass unlimited parameters through ajax due to being relatively new at it. Each location is available to be selected by checking the corresponding checkbox. Here is my code I'm trying to pass below.



//Example Checkbox
<input type="checkbox" checked name="locationID1" class="locationID" value="47">

$(".layer-button").click(function(){
var form = $(this).parents('form:first');
var locationID = [];
var n = 0;
$(".locationID", form).each(function () {
if(this.checked){
// part I'm having troubles with.
locationID[n] = $(this).val();
n++;
}
});

var data = {
"action":"addLayer",
"map-try-ok":"1",
// part I'm having troubles with.
"location_id":locationID
}


$.ajax({
type: "POST",
url: "/ajax/map/map.php",
dataType: "json",
data: data,
success: function(data) {
jQuery.each( data, function( key, val ) {
geocoder = new google.maps.Geocoder();
var color = $("select[name=color]", form).val();
var address = val["address"];
geocoder.geocode( { 'address': address}, function(results, status) {
if(results){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: "../image/icons/map/icon_marker"+color+".png",
title: val["name"],
url: ""
});
}
});

});




},
error: function(){return false;}
});

});


The code works great if I'm passing static numbers like.



var data = {
"action":"addLayer",
"map-try-ok":"1",
"location_id":"47"
}


Is there an optimal way of passing arrays through data passed through ajax? I'm not sure if its possible to run an each function right in the parameters of var data?


UPDATE:


I'm passing all this information to PHP script. PHP's return info to jquery works fine and I'm having no problems with the actual Google Maps API itself. The issue is passing [x] variables from jquery -> ajax -> php


I've attempted to call location_id with the following code and it completely passes the chunk of code leading me to believe the passing of the array did not work.



if(is_array($_POST['location_id'])){
foreach($_POST['location_id'] as $location_id){
echo "ID: ".$location_id."<br />";
}
}




Aucun commentaire:

Enregistrer un commentaire