Accessing parts of a php array in a javascript for loop - javascript

I'm trying to access and display elements of a php array in a javascript for loop, whenever I try and log out a value it always returns blank and I can't figure out why.
for(let i=0;i<"<?php echo sizeof($response['results']); ?>"; i++) {
console.log(i);
let divElement = document.createElement("div");
divElement.className = "col col-6 col-md-4 col-lg-3";
let h4Name=document.createElement('h4');
h4Name.className="name";
h4Name.innerHTML="<?php echo $response['results'][i]['name']?>;"
console.log("<?php echo $response['results'][i]['name']?>");
divElement.appendChild(h4Name);
let h4Address=document.createElement('h4');
h4Address.className="address";
h4Address.innerHTML="<?php echo $response['results'][i]['formatted_address']?>";
divElement.appendChild(h4Address);
document.querySelector(".row").appendChild(divElement);
}

You can't loop thru a JS array and access a corresponding PHP array. PHP is a back end code and JS (in this case) is a front end code.
One option you have is to have a result variable in javascript and use that array to loop.
Like:
//Put the PHP array into a JS variable
const results = <?php echo json_encode( $response['results'] );?>
//Loop thru the JS variable
for (let i = 0; i < results.length; i++) {
//Access object property as results[i]['formatted_address'] or results[i].formatted_address
//.........
}

Related

HTML collection getting parsed to JavaScript through PHP when it should be a String

I have a database that I use to create a resource of string values for example
|Boxers|1|
|Shirts|2|
etc
I then use php to populate a array with this resource
eg
$myArr = arrary['Boxers', '1', 'Shirts', 2]
then I parse the array as a JavaScript array through an echo and .push() each element within a for loop
This JS array then becomes the argument of a JS function call.
As you can see below.
<?php
if(isset($_SESSION["username"])){
$cartArr = array();
$sql = "SELECT item, quantity FROM shop_cart WHERE user = 'Mike'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
array_push($cartArr,$row["item"],$row["quantity"]);
}
}
echo '<script> let paramArr = [];';
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push(' . "$cartArr[$x]" . ');';
}
echo 'cleanUpVue(paramArr);
</script>';
}
?>
The problem is that every element that is a String such as Boxers, Shirts keeps getting parsed as an HTML Collection and not just as a String. I'd like to know what I can do to avoid this behavior? As all I need is a JS array of String elements (4 as per the example) and nothing else
terrible what an obvious oversight on my part, I simply forgot to include quotation marks before concatenating the variable name, as such JS was trying to evaluate the original Strings as they also matched id's within the DOM
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push("' . $cartArr[$x] . '");';
}

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.

Get Javascript variable as an index with PHP array in Javascript

Want javascript variable as index variable in php array in javascript.
Code is not working .....
<script>
var total = <?php echo count($resvalue); ?> ; //$resvalue is an array holding the values are 1,2,3,4. total will hold count of that array.
for(var j=0;j<total;j++)
{
<php echo $resvalue[j]; ?> // where j is javascript variable and $resvalue is PHP array
}
</script>
You cannot read values in a php array from javascript. Instead echo the array and turn it into a javascript array and let javascript do the count.
<script>
var resvalue = [<?php echo $resvalue; ?>]; // or something like this
for(var j=0; j < resvalue.length; j++)
{
// your value is available in the js-array
// resvalue[j]
}
</script>

javascript object push how to set key value

Is there any way to set own key value when using javascript push method? Here is my example:
<script>
var examples = [];
</script>
<?php foreach($examples as $example):?>
<script type="text/javascript">
var example<?php echo $example['id']?> = {
id : '<?php echo $example['id']?>',
another : '<?php echo $example['another']?>',
};
//here I would like to give key $example[id]
examples.push(example<?php echo $example['id']?>);
</script>
<?php endforeach;?>
<script>
for (index = 0; index < examples.length; ++index) {
somefunction(examples[index]);
}
</script>
For some reasons I need $example['id'] to have the same value as pushed key.
Making an array is making this a bit harder than you need it to be if you need the IDs to match.
If you want to reference it by the ID, you can simply use a vanilla JS object
<script>
var examples = {};
</script>
<?php foreach($examples as $example):?>
<script type="text/javascript">
var example<?php echo $example['id']?> = {
id : '<?php echo $example['id']?>',
another : '<?php echo $example['another']?>',
};
//here I would like to give key $example[id]
examples['' + <?php echo $example['id']?>] = example;
</script>
<?php endforeach;?>
<script>
for (var k in examples) {
somefunction(examples[k]);
}
</script>
This will let you set arbitrary string keys and loop through just like an array.
Use an object instead:
var examples = {};
...
examples[key] = value;
If your id is a string value, then you need a mapping object (var obj = {}; obj[key] = value), but you wan't be able to use it as an array since it's not an array, though, you still can do something like this: for (var k in elements) { if (elements.hasOwnProperty(k)) {do something} }
If you really want to use an Array than you can try using splice ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice ) method to insert your elements at certain index (just make sure that array length is always greater than index value you are trying to insert at), but for that your id has to be numeric, not a stirng.

Javascript array which contains arrays

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.

Categories

Resources