Javascript array which contains arrays - javascript

I have two Javascript arrays which have been populated by a forloop.
I now want to assign both of those arrays to a new array. However, the two arrays are being called within another function. So, I want to assign the function, containing the two arrays to a new array.
The idea is to use a while loop to populate the new array with the two existing arrays.
The difficulty is that the browser does not seem to like assigning an array to the google.maps function: eg: myarray[i] = (google.maps.LatLng(array1[i],array2[i]))
Here is the whole code... the actual bit that is going wrong is contained within the while loop toward the end of the code (the rest of it before the while loop works fine).
while($row = mysqli_fetch_array($marker_result)) {
$marker_location[] = $row["location"];
$marker_lat[] = $row["lat"];
$marker_lng[] = $row["lng"];
} //End of while loop
?>
<script>
//Converting php marker arrays to javascript marker arrays for use in for loop
var js_markerloc_array= <?php echo json_encode($marker_location ); ?>;
var js_markerlat_array= <?php echo json_encode($marker_lat ); ?>;
var js_markerlng_array= <?php echo json_encode($marker_lng ); ?>;
var markerloc_array = new Array(js_markerloc_array.length);
var markerlat_array = new Array(js_markerloc_array.length);
var markerlng_array = new Array(js_markerloc_array.length);
for(var i=0; i<js_markerloc_array.length; i++){
var jsloc = js_markerloc_array[i];
var jslat = js_markerlat_array[i];
var jslng = js_markerlng_array[i];
markerloc_array[i] = jsloc;
markerlat_array[i] = jslat;
markerlng_array[i] = jslng;
}
// Now need to write all of this below into an array so that it can populate markers from it! The difficulty is that the browser does not seem to like assigning the google.maps.LatLng(array1[i],array2[i]) to a new array
//var mapmarker_array = new Array(js_markerloc_array.length);
i = 0;
while (i < js_markerloc_array.length)
{
var mapmarker_array = new (google.maps.LatLng(markerlat_array[i], markerlng_array[i])); //Uses coordinates from database "markers" table
var test_marker1 = new google.maps.Marker({position:mapmarker1, title: markerloc_array[i]});
document.write(mapmarker1);
document.write(markerloc_array[i]);
i++;
}

I am Honestly not surprised this is not working.
Using new Array(x) can always behave unexpectedly.
It is much better to always use [] to create an array in Javascript. The top half of your script should be something like this:
<script>
var js_markerloc_array= JSON.parse('<?php echo json_encode($marker_location ); ?>');
var js_markerlat_array= JSON.parse('<?php echo json_encode($marker_lat ); ?>');
var js_markerlng_array= JSON.parse('<?php echo json_encode($marker_lng ); ?>');
var markerloc_array = [];
var markerlat_array = [];
var markerlng_array = [];
for (var i=0; len = js_markerloc_array.length; i < len; i++){
markerloc_array[i] = js_markerloc_array[i];
markerlat_array[i] = js_markerlat_array[i];
markerlng_array[i] = js_markerlng_array[i];
}
You also need to Parse the Json again on the javascript side once the script executes, it looks confusing but you need to wrap the php json_encode(x) in JSON.parse() which is Javascripts method for parsing json.
i = 0;
while (i < js_markerloc_array.length)
{
var mapmarker_array = new (google.maps.LatLng(markerlat_array[i], markerlng_array[i])); //Uses coordinates from database "markers" table
var test_marker1 = new google.maps.Marker({position:mapmarker1, title: markerloc_array[i]});
document.write(mapmarker1);
document.write(markerloc_array[i]);
i++;
}
</script>
I dont know what your are tying to refere to above with mapmarker1, so I cant help you with that, and havent ever used google.maps API before so I cant help any further, but I hope what I have said will help you!!

OK, it works! Here is the code:
while($row = mysqli_fetch_array($marker_result)) {
$marker_location[] = $row["location"];
$marker_lat[] = $row["lat"];
$marker_lng[] = $row["lng"];
} //End of while loop
?>
<script>
//Converting php marker arrays to javascript marker arrays for use in for loop
var js_markerloc_array= <?php echo json_encode($marker_location ); ?>;
var js_markerlat_array= <?php echo json_encode($marker_lat ); ?>;
var js_markerlng_array= <?php echo json_encode($marker_lng ); ?>;
var mapmarkers = [];
var testmarkers = [];
i = 0;
for (var i = 0; i < js_markerloc_array.length; i++) {
mapmarkers[i] = new google.maps.LatLng(js_markerlat_array[i], js_markerlng_array[i]);
testmarkers[i] = new google.maps.Marker({position: mapmarkers[i], title: js_markerloc_array[i]});
}
Then further down the page (after the google maps initialise function and options)...
i = 0;
for (var i = 0; i < js_markerloc_array.length; i++) {
testmarkers[i].setMap(map);
}
So, from top to bottom. While loop places database query results into 3 PHP arrays (one for location, one for latitude and one for longitude).
These are then converted to 3 corresponding JavaScript arrays.
Then 2 new JavaScript arrays are created which take their values from the other 3 arrays as shown in the forloop, the 3 arrays are included in googlemaps functions (which was the main thing causing problems before).
Note in this forloop that there is a mapmarkers array which specifies the lat and lng, then a testmarkers array which specifies the position given by the mapmarkers array AND allocates the location name.
It is then the testmarkers array which is called in the forloop further down the page.
This second forloop simply takes the testmarkers array which contains the lat,lng and location and uses the setMap google maps API function to place the marker on the map!
Hence users can now add their own markers to the database, and these can then be added automatically. Hope this helps someone, and thanks for the help and for pointing out my bloated code, constructive criticism very welcome. Thanks again.

Related

Passing array data from php to javascript using a loop

Is there a similar way to implement this kind of "algorithm" in the right way?
for(i=0;i<howManyCourses;i++){
var stored = "<?php echo $buf[i] ?>";
var option = document.createElement("option");
option.text=stored;
e.add(option);
}
So I want to pass the data from the $buf array into a javascript variable. I've tried many ways but it seems like I cannot find the solution. I'm new into php and I apologise for any obvious mistake.
It should be in the same file or in another case AJAX will be the solution.
<script type="text/javascript">
const arr = <?php echo json_encode($buf); ?>;
for (var i = 0; i < arr.length ; i++) {
//do something
}
</script>
If you need that JS' variable buf contain the same elements as PHP's $buf, you can do the following:
var buf = <?php echo json_encode($buf); ?>;
Just keep in mind that if PHP's $buf is not an indexed array, JS' buf will be an object instead of an array.

Populating a Select Box with Data from Google Sheet

I have a Google site and am currently using the following script to populate my select box with data from the google sheet that is serving as my database:
<? var stringified = getData(); ?>
<?var data = JSON.parse(stringified)?>
<select size="10" id="userChoice">
<? for (var i = 0; i < data.length; i++) { ?>
<option>
<?= data[i] ?>
<? } ?>
</select>
This loads the page with the select box populated with every entry in the database. I'm wondering if this is the best way to go about it. What I would really like to do is have the contents of the select box be a little more dynamic.
I wrote out a script to filter through (by date) the contents of the Google Sheet, but I can't quite figure out how to have those filtered results show up in the above select box. I've tried several possible solutions, but keep hitting road blocks with them. Below is the function on the client side that passes the dates to the server side (note that I realize nothing in the below scripts would pass the data back to the select box. This is just to show how I am filtering through the data):
//Takes the dates that were entered into the first two date pickers and sends them over to the server side stringified. The server side then uses these dates to filter out jobs not within the given time period.
function dateFilter(){
var date = {};
//dates pusehd into array
date[0] = document.getElementById("startDate").value;
date[1] = document.getElementById("endDate").value;
//array stringified
var dates = JSON.stringify(date);//Convert object to string
google.script.run
.getData2(dates);
Then here is the code that filters through the database on the server side:
function getData2(dates) {
var ss = SpreadsheetApp.openById('1emoXWjdvVmudPVb-ZvFbvnP-np_hPExvQdY-2tOcgi4').getSheetByName("Sheet1");
var date = JSON.parse(dates);
var dateArray = [];
for (var k in date) {//Loop through every property in the object
var thisValue = date[k];//
dateArray.push(thisValue);
};
var startDate = Date.parse(dateArray[0]);
var endDate = Date.parse(dateArray[1]);
var jobReference = [];
var job;
var dateCell1;
var dateCell;
if ((startDate==NaN) || (endDate==NaN)){
for (var i = 2; job!=""; i++){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
};
}
else{
for (var i = 2; job!=""; i++){
dateCell1 = ss.getRange(i,3).getValue();
dateCell = Date.parse(dateCell1);
if (startDate<=dateCell&&endDate>=dateCell){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
Logger.log("here it is"+jobReference);
}
else{
}
}
};
var jR = JSON.stringify(jobReference);
return jR;
}
Now I've tried several things, having a success handler change the line <? var stringified = getData();?> to use getData2 doesn't seem to work (it yells at me that variable I'm trying to parse is undefined on the server side). So I tried putting an if/else in that would only have it parse if the variable was != to undefined, that didn't work either. Any suggestions would be appreciated.
I figured it out! This is functional, but perhaps not best practices, so if someone has any input, feel free to chime in.
So the first bit of code on the client side for the select box I left the same.
The next bit, where I send the dates over to the server side was changed to this:
function dateFilter(){
var sdate = document.getElementById("startDate").value;
var edate = document.getElementById("endDate").value;
google.script.run.withSuccessHandler(dateSuccess)
.getData2(sdate,edate);
}
So, since it was only two variables I took out the part that pushed it to an array. This eliminated the problem of parsing on the server side and thus having an undefined variable. I also added a success handler.
The server side code was left essentially the same, however I did change the for loop slightly. Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); and had it loop though until i<= last. This kept the code from timing out on me.
Next I added the function I used for the success handler:
function dateSuccess(jobs){
document.getElementById('userChoice').options.length = 0;
var data = JSON.parse(jobs)
for (var i = 0; i < data.length; i++) {
var option = document.createElement("option");
option.text = data[i]
var select = document.getElementById("userChoice");
select.appendChild(option);
}
}
Works like a charm!
Scriptlets i.e. <? ?> are compiled and run when the page is created using execute function. They are not for dynamic modification of the web page. To modify the options based on a server returned data, in this case from getData(). You would do something like this
Firstly you set your google.script to call modifyoptions function on success
google.script.run.withSuccessHandler(modifyOptions)
.getData2(dates);
The above will code will automatically pass the return value of getData2 i.e Jr value to modifyOptions function
function modifyOptions(jobReference){
var selOpt = document.getElementById("userChoice")
selOpt.innerHTML ="" // Remove previous options
var options = ""
var data = JSON.parse(jobReference)
for (var i = 0; i < data.length; i++) {
options += "<option>"+data[i] +</option> //New string of options based on returned data
}
selOpt.innerHTML = options //Set new options
}
You can find a working example of how to modify the select-options in javascript here
Hope that helps!

For loop issue - javascript - php - google maps

I'm using this for loop in javascript and I'm trying to create polygons on a google map with data retrieved from database. my problem here is that i have included php inside the javascript and each time the for loop runs the value of $i is never changed. anyone can help??
enter code here
<?php $i = 0 ?>;
for(i =0; i< <?=$length?>; i++)
{
var coordinates = "<?=$districtsarray[$i]['coords']?>";
var coordinates = coordinates.substr(1, coordinates.length-2).split("),(");
var souniCoordinates = coordinates.map(function(pointString){
var latlon = pointString.split(", ");
return new google.maps.LatLng(latlon[0], latlon[1]);
});
var SouniCoords = [souniCoordinates];
<?php echo $districtsarray[$i]['name']?> = new google.maps.Polygon({
paths: SouniCoords,
strokeColor: '#383838 ',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#CD5C5C ',
fillOpacity: 0.5
});
<?php echo $districtsarray[$i]['name']?>.setMap(map);
<?php $i=$i+1;?>
}
</script>
<?php
In my opinion mixing PHP and JavaScript like this makes code hard to read and maintain. I would recommend using the PHP function json_encode (http://php.net/manual/en/function.json-encode.php) to convert your PHP data structure into JSON and echo it out in one place.
Then use JSON.parse() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse to convert the string into a JavaScript object.
So it might look something like this:
var data = JSON.parse(<?php echo json_encode($data); ?>);
Then only use JavaScript after this point :).
step 1) take value of php variable into a javascript variable like this
var javascriptarray = JSON.parse('< json_encode($districtsarray); ?>');
step 2) now use "javascriptarray" & javascript variable "i" in loop to access its elements like this
var coordinates = javascriptarray[i]['coords'];
Firstly, please understand that the above is bad practice as it makes maintenance/debugging somewhere between awkward and impossible. If you are insistent on doing so, a better alternative would be to use string interpolation:
<?php
echo <<< END
//always use K&R style for js because of automatic ; insertion:
for (var i=0, i < $length, i++) {
//do stuff
}
END
?>
The way you have written it 'i' has no definition in javascript, incrementing undefined does not have a meaningful result. Because of these kinds of problems you should not mix javascript and php like this. A better alternative is:
$.getJSON('myPHP.php', function(response) {
var data = JSON.parse(response);
for (index in data) {
var row = data[index]
//do stuff
}
})
This uses jquery although it is certainly possible to achieve this with raw js, it just takes more code. Have the php script 'myPHP' return an array with the records from the db.

XML to JavaScript Array [Google Maps]

I need create Javascript array from xml ..
I`v get xml data from poly php with ajax. Everything is ok.
I must create array like that:
point = [
new google.maps.LatLng(40.9921196514,47.8604733650 ),
new google.maps.LatLng(40.9922511293,47.8606186245 ),
];
Code
downloadUrl("poly.php", function(data) {
var xml = data.responseXML;
var polys = xml.documentElement.getElementsByTagName("poly");
for (var i = 0; i < polys.length; i++) {
var pid = polys[i].getAttribute("pid");
point = [
new google.maps.LatLng(parseFloat(polys[i].getAttribute("plat")), parseFloat(polys[i].getAttribute("plng")) );
];
i`ve do that but it does not work.. ((
P.S. I get data from MySQL.
...
Xml:
<polys>
<poly pid="1" pstatus="status1" plat="40.992638" plng="47.860474"/>
<poly pid="2" pstatus="status2" plat="40.992252" plng="47.860619"/>
</polys>
May I assume you use the function downloadUrl from googles util.js ?
When yes: data is already a document, there is no need to access data.responseXML
Each attempt to access a property of xml will result in an error, because xml is undefined
Replace this:
var xml = data.responseXML;
var polys = xml.documentElement.getElementsByTagName("poly");
with:
var polys = data.documentElement.getElementsByTagName("poly");
There is an syntax-error:
point = [
new google.maps.LatLng(parseFloat(polys[i].getAttribute("plat")), parseFloat(polys[i].getAttribute("plng")) );
];
remove the semicolon:
("plng")) );
//---------^
But to get the desired result you must create the point-array outside the loop:
var point=[];
and add the LatLng's to point inside the loop:
point.push(new google.maps.LatLng(parseFloat(polys[i].getAttribute("plat")),
parseFloat(polys[i].getAttribute("plng"))));

Convert js Array() to JSon object for use with JQuery .ajax

in my app i need to send an javascript Array object to php script via ajax post. Something like this:
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
alert(saveData);
$.ajax({
type: "POST",
url: "salvaPreventivo.php",
data:saveData,
async:true
});
Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work.
Ideas?
Thanks in advance
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
//creating a json object
var jObject={};
for(i in saveData)
{
jObject[i] = saveData[i];
}
//Stringify this object and send it to the server
jObject= YAHOO.lang.JSON.stringify(jObject);
$.ajax({
type:'post',
cache:false,
url:"salvaPreventivo.php",
data:{jObject: jObject}
});
// reading the data at the server
<?php
$data = json_decode($_POST['jObject'], true);
print_r($data);
?>
//for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
//include the follwing files
//<!-- Dependencies -->
//<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
//<!-- Source file -->
//<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
Hope this helps
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
There is no need of converting it into JSON because its already a json object.
To view the same use json.toSource();
When using the data on the server, your characters can reach with the addition of slashes eg
if string = {"hello"}
comes as string = {\ "hello \"}
to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>

Categories

Resources