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.
Related
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.
I'm trying to execute some PHP code, and then afterward use Javascript to take one of my PHP variables and use it to open a new window with that variable's contents on it in CSV format.
This works when my PHP variable is relatively small (i.e. 1,000 entries), but when I execute it on code that has for example about 20,000 entries in the array, it stops in the PHP code below without throwing any errors. What could be my issue? Yesterday I traced the issue to array_column - that the code would simply stop executing once it got to that line. However, it did it again today, even without that function and I gathered that there must be a bigger issue. I've re-included those array_column() calls since I assume they're not the real problem. Here's the PHP code:
function generateTextFile(){
$array = $_SESSION["array"];
$hostCol = array_column($array, "host");
$timeCol = array_column($array, "Time");
$col3 = array_column($array, "col3");
$col4 = array_column($array, "col4");
$signalCol = array_column($array, "Signal");
for($x = 0; $x < count($timeCol); $x++){
if(!isset($array[$x]["host"])){
$hostCol[$x] = $_GET['hostname'];
}
else{
$hostCol[$x] = $array[$x]["host"];
}
}
$subArray = array($hostCol, $timeCol, $col3, $col4, $signalCol);
$out = array();
foreach($subArray as $rowkey => $row){ // invert the array
foreach($row as $colkey => $col)
$out[$colkey][$rowkey] = $col;
}
$text = "";
for($x = 0; $x < count($out); $x++){
$curText = implode(",", $out[$x]);
$text = $text . $curText . "<br>";
}
$_SESSION['text'] = $text;
}
Is there something I'm doing wrong in the above PHP code? It just builds an array and then makes another variable in CSV format. I declared the script in the section of my HTML, after the above function is called. I'd be very grateful for your insight.
PHP have the thing called "time limit" to proccess the scripts.
The default is 30 seconds, and you can change this:
set_time_limit( int $seconds );
I had the same issue trying to proccess about 6.000 CSV's, and solved with this method.
Hope you find this useful!
I know this kind of post is frequently found on internet. But my problem is a little bit more dificult and I did not find an answer.
I want to make an associative array in Javascript in a loop with a variable name.
($JJ = table of object)
($JJ->getResto($DB,$acad) allows me to recover my database datas)
$JJ = new RestaU();
$JJ = $JJ->getResto($DB,$acad);
for ($i = 0; $i <= sizeof($JJ)-1; $i++) {
//Datas recovering
$lat = $JJ[$i]->loc_lat;
$long = $JJ[$i]->loc_long;
$name = $JJ[$i]->nom;
$ville = $JJ[$i]->ville;
//String treatment to avoid spaces
$ville = str_replace(" ","",$ville);
$name = str_replace(" ","",$name);
echo <<< SC
<script>
//here $ville will contain an google map object associated to the ville name.
//It means that I need to change it for each "for" loop.
var $ville = new Object();
//that is why here I need to have $ville["name"] to generate a table for each city
//and have an access to it later.
$ville+["name"] = new google.maps.LatLng($lat,$long);
console.log(string2);
</script>
SC;
My problem is, I can not find the solution to right for example ville1["name"]. Each time the code is not "interpreted" it means I can have the string but it does not create my array.
Thank you a lot for all your ideas!
SOLUTION IN COMMENT.
I used that :
var string = "$ville";
window[string]["name"] = "blabla";
It works really well.
php is server language and javascript is clint browser language!
in fact you can't share variables!
But you can print variables to javascript code like:
<script>
var myvar = '<?php echo $myvar; ?>';
</script>
if you want to send variables from javascript to php you must use Ajax
for array
<script>
<?php
$array = array('index1'=>'hellow World!','index2'=>'Iran haven`t nuclear bomb');
echo 'var arryname = new Array();';
foreach($array as $key=>$val){
echo "\n arryname['{$key}'] = '{$val}';";
}
?>
</script>
Let's say I have a javascript array with a bunch of elements (anywhere from 50-200).
I want to send that to PHP (prepared statement) using ajax. Currently, I .load a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.
array[i] = variable;
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.
AJAX requests are no different from GET and POST requests initiated through a <form> element. Which means you can use $_GET and $_POST to retrieve the data.
When you're making an AJAX request (jQuery example):
// JavaScript file
elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})
It's (almost) equivalent to posting this form:
<form action="/test.php" method="post">
<input type="text" name="elements" value="1,2,9,15">
</form>
In both cases, on the server side you can read the data from the $_POST variable:
// test.php file
$elements = $_POST['elements'];
$elements = explode(',', $elements);
For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.
Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:
function obj2url(prefix, obj) {
var args=new Array();
if(typeof(obj) == 'object'){
for(var i in obj)
args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
}
else
args[args.length]=prefix+'='+encodeURIComponent(obj);
return args.join('&');
}
prefix is a parameter name.
EDIT:
var a = {
one: two,
three: four
};
alert('/script.php?'+obj2url('a', a));
Will produce
/script.php?a[one]=two&a[three]=four
which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.
So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.
Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.
You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>
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.