Reputation: 12947
I'm trying to store a user ID (key) and an array of GPS coordinates using an object in JavaScript, but for some reason each time a new set of coordinates is added (when it pulls from the database), it overwrites the previous coordinates in the array (value) instead of appending.
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var loc = {};
user_id = data[0];
lati = data[1]; //get id
longi = data[2]; //get name
var myLatlngt = 'new google.maps.LatLng(' + lati + ',' + longi + ')';
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
loc[user_id].push(myLatlngt);
console.log('loc :::', loc);
Here's the log:
Resource interpreted as Other but transferred with MIME type undefined.
map2.php:50loc ::: Object
86ad04fb-1da5-4118-8b00-942676d62387: Array[1]
0: "new google.maps.LatLng(51,-82)"
length: 1
__proto__: Array[0]
__proto__: Object
The long number (86ad04...) is the user ID (key), but if I send new coordinates it overwrites instead of appending. I would appreciate any help I can get.
Thanks
Upvotes: 0
Views: 1480
Reputation: 74655
you need to place var loc = {};
outside of your ajax callback so that its state is preserved over multiple ajax requests.
Upvotes: 0
Reputation: 143139
Because you empty loc
every time you enter the function:
var loc = {};
Upvotes: 2