I am trying to append a the variable imagename but instead of displaying a file name, it is appending numbers ‘0’ then break then ‘1’. I want to know why is it appending these numbers and not the file names? The imagename variable loops through the imageNameArray variable which contains a $_SESSION variable which retrieves the name of the files which have been uploaded and that $_SESSION variable is retrieved from the php script where the files are uploaded.
Below is the javascript code where the appending occurs:
function stopImageUpload(success){
var imageNameArray = <?php echo json_encode(isset($_SESSION ['fileImage']) ? $_SESSION ['fileImage'] : null); ?>;
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (imagename in imageNameArray)
{
$('.listImage').append(imageNameArray[imagename]+ '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is the php script where it uploads a file and where the $_SESSION variable retrieve its file name:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
because you’re using a
for inloop on an array,imageNamewill be equal to the array indeces, not its values. Much likefor (i in window),where i will list all methods and properties of the window object.Since this is an array, I strongly recommend you use a
for(i=0;i<arr.length;i++)type of loop, because it’s just safer… in both cases you will need to replacewith
EDIT
The
forloop probably din’t work for you because I left out a bit, because I thought it to be obvious. Unfortunately, obvious things are easy to overlook… as Greg pointed out to me (thx m8) :if you use the for(i…) style loop. I’ll just add the full loop for clarity:
To help you further in finding out what might be causing the problem with only one img name showing up, add this right before the loop begins:
console.log(imageArrayName);and look at your console. Does the array contain more than 1 element? what does it say? While you’re at it, try adding this line, too:console.log((imageArray instanceof Array ? 'for' : 'for-in'));. Add this line anywhere in the JavaScript function you posted, but outside the loop to avoid cluttering your console all to much…Let me know what you find out