Array [document.getElementById().value][2] not working

Hi, hello everyone this is my first post. I have exhausted manuals and tutorials and posts and I can’t get this to work.
Hope somebody here can help me.

I have a mySql query then from the data an array is created. With values from the array a dropdown list for a form is created. Then a javascript array is created from the php array. and an onchange() function is trying to change an image in a field, using the ID value from the dropdown list selection (dropd.value) as key in the Array (to display the image name).

<?PHP
include 'open_connection_con.php';
$prod_query = mysqli_query($con,"SELECT id, type, image_name, description FROM Products");
					
$products = array();
while($row = mysqli_fetch_array($prod_query))
	{
		$products[] = $row;
	}
					
// then I create a dropdown list within a form.
echo "<select name='prodType' id='prodDrop' onchange='swapProd()'>";
echo "<option value='0'>Select one:</option>";
foreach ($products as $row)
	{
		echo "<option value='" . $row['id'] . "'>" . $row['type'] . "</option>";
	}
echo "</select>";

mysqli_close($con);
?>
<script type="text/javascript">

// pass the php array into a javascript array.
var prodArrJS = <?php echo json_encode($products);?>

// and the function to display the image (on <img id="prodImage">) of the selected product from the dropdown list above
function swapProd()
{
var image = document.getElementById("prodImage");
var dropd = document.getElementById("prodDrop");
image.src = "images/ex/" + prodArrJS[dropd.value][2] + ".jpg";
var p1=document.getElementById("lar");
p1.value="x"
}
</script>
<?php
unset( $products );
?>

The image at the end of the function is not displayed (nothing is displayed, not even the little question mark) and the function stops.
I have tested the array with numbers and strings and it works ok.
Thanks in advance.
R.Mars

Hi robert.mars, welcome to the forums,

Shouldn’t “value” be “selectedIndex.value”?

no, the value gets picked up from the <form><select><option> dropdown list generated in the PHP here:

...
echo "<select name='prodType' id='prodDrop' onchange='swapProd()'>";
...
foreach ($products as $row)
	{
		echo "<option value='" . $row['id'] . "'>" . $row['type'] . "</option>";
	}
echo "</select>";
...

with the $row[“id”] from the original PHP “$products” Array as value for the option,
then via “.getElementById” on the function to the var dropd here:

function swapProd()
{
...
var dropd = document.getElementById("prodDrop");
image.src = "images/ex/" + prodArrJS[dropd.value][2] + ".jpg";
...
}

The “prodArrJS” javascript Array where I’m trying to use dropd.value as index was created here (in the script before the function):


...
var prodArrJS = <?php echo json_encode($products);?>
...

So if you temporarily try this (not the most elegant way perhaps but it works)


function swapProd()
{
var image = document.getElementById("prodImage");
var dropd = document.getElementById("prodDrop");
/* next line for troubleshooting only */
alert(dropd.value);
image.src = "images/ex/" + prodArrJS[dropd.value][2] + ".jpg";
var p1=document.getElementById("lar");
p1.value="x"
}

you get an “index” and not “undefined”?

The alert throws the correct value: 47, 60, 61, etc. depending on the choice.
dropd.value works everywhere else I have tested it except in the Array.

Ah. I think I see the problem now.

json_encode returns a string not an array

Try tossing json_decode into the mix.

Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.

Thanks Mittineague,

I’m not a complete newbie but I’m getting my keyboard dusted off after a LOT of years, so I’m going to need it a little more literal.

Are you saying I should replace

var prodArrJS = <?php echo json_encode($products);?>

with

var prodArrJS = <?php echo json_decode($products);?>

?

Sorry :blush:
I hope you didn’t spend much time or thought on that.

I was right that the string needs to be changed to an array, but way off on how to approach it.
One, I was thinking PHP-centric instead of javascript
Two, because of security risk if not used carefully, I have a mental-block against even thinking of using eval()

As long as you are using your own data and know it won’t contain anything malicious this should work

var prodArrJS = eval(<?php echo json_encode($products);?>);

jaja, I hope I didn’t sound too lazy. :cool: I spent more than a day searching the web on how to get that thing working that once I got into posting in the forums I turned the switch and expected to get the answer ready-made. I realize I need to get back on research mode for the things that are new to me.

So…

It has to be javascript because I’m using several values from the array in math operations with the form input field values, and other form fields populated depending on the dropdown list choice.

Then, You mean to say that

var prodArrJS = <?php echo json_encode($products);?>

the variable prodArrJS (javascript) is not an array? it came from the array $products (php) .

Also, as we are getting into changing this It might be important to mention that while I was checking the page source I found this:

var prodArrJS = [{"0":"37","id":"37","1":"xxx","type":"xxx","2":"yyy","image_name":"yyy","3":"zzz","description":"zzz "},{"0":"38" etc. ... ...}]

The values are duplicated, it is using numbers as keys but also the table’s column’s names from the query. This is not the cause of my problems with “dropd.value” though.

I get this on the page source:

var prodArrJS = eval(<br />
<b>Notice</b>:  Undefined variable: products in <b>/index.php</b> on line <b>251</b><br />
null);

using:

var prodArrJS = eval(<?php echo json_encode($products);?>);

hmm, why did my previous previous post needed to get moderated and my previous (I get this on the page source: …) didn’t?

Off-Topic:
The forums use various ways to stop SPAM. They do a good job but unfortunately they sometimes stop non-SPAM

It might be easier if you post (or PM me) a link to the page if it’s online.
Believe me, I know how frustrating troubleshooting can be, and the solutions are often simple and have been staring you in the face the whole time.

Change back to

var prodArrJS = <?php echo json_encode($products);?>

and try

function swapProd()
{
var image = document.getElementById("prodImage");
var dropd = document.getElementById("prodDrop");
/* next line for troubleshooting only */
alert(typeof prodArrJS);
image.src = "images/ex/" + prodArrJS[dropd.value][2] + ".jpg";
var p1=document.getElementById("lar");
p1.value="x"
}

Does it give you "string, “array”, or “object”?

Going by your “checking the page source I found this:” it looks to be an array of objects.

I just realized something, you mentioned earlier that it would be preferable a php array than a javascript.
Could I create a global array variable? Global means that even if you change from one page to another the variable remains and can be used in all pages right?
That would work better for me that what I have been trying to do with the “query to php array to javascript array”.

ah, no, scratch that. I forgot I need the dynamic javascript array for the dropdown list selection.

alert(typeof prodArrJS); returns “object”.

Well, it’s getting narrowed down a bit.

Try

function swapProd()
{
var image = document.getElementById("prodImage");
var dropd = document.getElementById("prodDrop");
/* alert lines for troubleshooting only */
alert("prodArrJS " + prodArrJS );
alert("prodArrJS[dropd.value] " + prodArrJS[dropd.value] );
alert("prodArrJS[dropd.value][2] " + prodArrJS[dropd.value][2] );
image.src = "images/ex/" + prodArrJS[dropd.value][2] + ".jpg";
var p1=document.getElementById("lar");
p1.value="x"
}

prodArrJS [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

prodArrJS[dropd.value] undefined

alert("prodArrJS[dropd.value][2] " + prodArrJS[dropd.value][2] ); doesn’t do anything, doesn’t show an alert box.

Im going to redo de array in javascript manually instead of using json.